title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Gensim - Documents & Corpus
Here, we shall learn about the core concepts of Gensim, with main focus on the documents and the corpus. Following are the core concepts and terms that are needed to understand and use Gensim − Document − ZIt refers to some text. Document − ZIt refers to some text. Corpus − It refers to a collection of documents. Corpus − It refers to a collection of documents. Vector − Mathematical representation of a document is called vector. Vector − Mathematical representation of a document is called vector. Model − It refers to an algorithm used for transforming vectors from one representation to another. Model − It refers to an algorithm used for transforming vectors from one representation to another. As discussed, it refers to some text. If we go in some detail, it is an object of the text sequence type which is known as ‘str’ in Python 3. For example, in Gensim, a document can be anything such as − Short tweet of 140 characters Single paragraph, i.e. article or research paper abstract News article Book Novel Theses A text sequence type is commonly known as ‘str’ in Python 3. As we know that in Python, textual data is handled with strings or more specifically ‘str’ objects. Strings are basically immutable sequences of Unicode code points and can be written in the following ways − Single quotes − For example, ‘Hi! How are you?’. It allows us to embed double quotes also. For example, ‘Hi! “How” are you?’ Single quotes − For example, ‘Hi! How are you?’. It allows us to embed double quotes also. For example, ‘Hi! “How” are you?’ Double quotes − For example, "Hi! How are you?". It allows us to embed single quotes also. For example, "Hi! 'How' are you?" Double quotes − For example, "Hi! How are you?". It allows us to embed single quotes also. For example, "Hi! 'How' are you?" Triple quotes − It can have either three single quotes like, '''Hi! How are you?'''. or three double quotes like, """Hi! 'How' are you?""" Triple quotes − It can have either three single quotes like, '''Hi! How are you?'''. or three double quotes like, """Hi! 'How' are you?""" All the whitespaces will be included in the string literal. Following is an example of a Document in Gensim − Document = “Tutorialspoint.com is the biggest online tutorials library and it’s all free also” A corpus may be defined as the large and structured set of machine-readable texts produced in a natural communicative setting. In Gensim, a collection of document object is called corpus. The plural of corpus is corpora. A corpus in Gensim serves the following two roles − The very first and important role a corpus plays in Gensim, is as an input for training a model. In order to initialize model’s internal parameters, during training, the model look for some common themes and topics from the training corpus. As discussed above, Gensim focuses on unsupervised models, hence it doesn’t require any kind of human intervention. Once the model is trained, it can be used to extract topics from the new documents. Here, the new documents are the ones that are not used in the training phase. The corpus can include all the tweets by a particular person, list of all the articles of a newspaper or all the research papers on a particular topic etc. Following is an example of small corpus which contains 5 documents. Here, every document is a string consisting of a single sentence. t_corpus = [ "A survey of user opinion of computer system response time", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", ] Once we collect the corpus, a few preprocessing steps should be taken to keep corpus simple. We can simply remove some commonly used English words like ‘the’. We can also remove words that occur only once in the corpus. For example, the following Python script is used to lowercase each document, split it by white space and filter out stop words − import pprint t_corpus = [ "A survey of user opinion of computer system response time", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", ] stoplist = set('for a of the and to in'.split(' ')) processed_corpus = [[word for word in document.lower().split() if word not in stoplist] for document in t_corpus] pprint.pprint(processed_corpus) ] [['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time'], ['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement'], ['generation', 'random', 'binary', 'unordered', 'trees'], ['intersection', 'graph', 'paths', 'trees'], ['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering']] Gensim also provides function for more effective preprocessing of the corpus. In such kind of preprocessing, we can convert a document into a list of lowercase tokens. We can also ignore tokens that are too short or too long. Such function is gensim.utils.simple_preprocess(doc, deacc=False, min_len=2, max_len=15). gensim.utils.simple_preprocess() fucntion Gensim provide this function to convert a document into a list of lowercase tokens and also for ignoring tokens that are too short or too long. It has the following parameters − It refers to the input document on which preprocessing should be applied. This parameter is used to remove the accent marks from tokens. It uses deaccent() to do this. With the help of this parameter, we can set the minimum length of a token. The tokens shorter than defined length will be discarded. With the help of this parameter we can set the maximum length of a token. The tokens longer than defined length will be discarded. The output of this function would be the tokens extracted from input document. Print Add Notes Bookmark this page
[ { "code": null, "e": 2157, "s": 2052, "text": "Here, we shall learn about the core concepts of Gensim, with main focus on the documents and the corpus." }, { "code": null, "e": 2246, "s": 2157, "text": "Following are the core concepts and terms that are needed to understand and use Gensim −" }, { "code": null, "e": 2282, "s": 2246, "text": "Document − ZIt refers to some text." }, { "code": null, "e": 2318, "s": 2282, "text": "Document − ZIt refers to some text." }, { "code": null, "e": 2367, "s": 2318, "text": "Corpus − It refers to a collection of documents." }, { "code": null, "e": 2416, "s": 2367, "text": "Corpus − It refers to a collection of documents." }, { "code": null, "e": 2485, "s": 2416, "text": "Vector − Mathematical representation of a document is called vector." }, { "code": null, "e": 2554, "s": 2485, "text": "Vector − Mathematical representation of a document is called vector." }, { "code": null, "e": 2654, "s": 2554, "text": "Model − It refers to an algorithm used for transforming vectors from one representation to another." }, { "code": null, "e": 2754, "s": 2654, "text": "Model − It refers to an algorithm used for transforming vectors from one representation to another." }, { "code": null, "e": 2957, "s": 2754, "text": "As discussed, it refers to some text. If we go in some detail, it is an object of the text sequence type which is known as ‘str’ in Python 3. For example, in Gensim, a document can be anything such as −" }, { "code": null, "e": 2987, "s": 2957, "text": "Short tweet of 140 characters" }, { "code": null, "e": 3045, "s": 2987, "text": "Single paragraph, i.e. article or research paper abstract" }, { "code": null, "e": 3058, "s": 3045, "text": "News article" }, { "code": null, "e": 3063, "s": 3058, "text": "Book" }, { "code": null, "e": 3069, "s": 3063, "text": "Novel" }, { "code": null, "e": 3076, "s": 3069, "text": "Theses" }, { "code": null, "e": 3345, "s": 3076, "text": "A text sequence type is commonly known as ‘str’ in Python 3. As we know that in Python, textual data is handled with strings or more specifically ‘str’ objects. Strings are basically immutable sequences of Unicode code points and can be written in the following ways −" }, { "code": null, "e": 3470, "s": 3345, "text": "Single quotes − For example, ‘Hi! How are you?’. It allows us to embed double quotes also. For example, ‘Hi! “How” are you?’" }, { "code": null, "e": 3595, "s": 3470, "text": "Single quotes − For example, ‘Hi! How are you?’. It allows us to embed double quotes also. For example, ‘Hi! “How” are you?’" }, { "code": null, "e": 3720, "s": 3595, "text": "Double quotes − For example, \"Hi! How are you?\". It allows us to embed single quotes also. For example, \"Hi! 'How' are you?\"" }, { "code": null, "e": 3845, "s": 3720, "text": "Double quotes − For example, \"Hi! How are you?\". It allows us to embed single quotes also. For example, \"Hi! 'How' are you?\"" }, { "code": null, "e": 3984, "s": 3845, "text": "Triple quotes − It can have either three single quotes like, '''Hi! How are you?'''. or three double quotes like, \"\"\"Hi! 'How' are you?\"\"\"" }, { "code": null, "e": 4123, "s": 3984, "text": "Triple quotes − It can have either three single quotes like, '''Hi! How are you?'''. or three double quotes like, \"\"\"Hi! 'How' are you?\"\"\"" }, { "code": null, "e": 4183, "s": 4123, "text": "All the whitespaces will be included in the string literal." }, { "code": null, "e": 4233, "s": 4183, "text": "Following is an example of a Document in Gensim −" }, { "code": null, "e": 4329, "s": 4233, "text": "Document = “Tutorialspoint.com is the biggest online tutorials library and it’s all free also”\n" }, { "code": null, "e": 4550, "s": 4329, "text": "A corpus may be defined as the large and structured set of machine-readable texts produced in a natural communicative setting. In Gensim, a collection of document object is called corpus. The plural of corpus is corpora." }, { "code": null, "e": 4602, "s": 4550, "text": "A corpus in Gensim serves the following two roles −" }, { "code": null, "e": 4959, "s": 4602, "text": "The very first and important role a corpus plays in Gensim, is as an input for training a model. In order to initialize model’s internal parameters, during training, the model look for some common themes and topics from the training corpus. As discussed above, Gensim focuses on unsupervised models, hence it doesn’t require any kind of human intervention." }, { "code": null, "e": 5121, "s": 4959, "text": "Once the model is trained, it can be used to extract topics from the new documents. Here, the new documents are the ones that are not used in the training phase." }, { "code": null, "e": 5277, "s": 5121, "text": "The corpus can include all the tweets by a particular person, list of all the articles of a newspaper or all the research papers on a particular topic etc." }, { "code": null, "e": 5411, "s": 5277, "text": "Following is an example of small corpus which contains 5 documents. Here, every document is a string consisting of a single sentence." }, { "code": null, "e": 5721, "s": 5411, "text": "t_corpus = [\n \"A survey of user opinion of computer system response time\",\n \"Relation of user perceived response time to error measurement\",\n \"The generation of random binary unordered trees\",\n \"The intersection graph of paths in trees\",\n \"Graph minors IV Widths of trees and well quasi ordering\",\n]" }, { "code": null, "e": 5941, "s": 5721, "text": "Once we collect the corpus, a few preprocessing steps should be taken to keep corpus simple. We can simply remove some commonly used English words like ‘the’. We can also remove words that occur only once in the corpus." }, { "code": null, "e": 6070, "s": 5941, "text": "For example, the following Python script is used to lowercase each document, split it by white space and filter out stop words −" }, { "code": null, "e": 6603, "s": 6070, "text": "import pprint\nt_corpus = [\n \"A survey of user opinion of computer system response time\", \n \"Relation of user perceived response time to error measurement\", \n \"The generation of random binary unordered trees\", \n \"The intersection graph of paths in trees\", \n \"Graph minors IV Widths of trees and well quasi ordering\",\n]\nstoplist = set('for a of the and to in'.split(' '))\nprocessed_corpus = [[word for word in document.lower().split() if word not in stoplist]\n for document in t_corpus]\n\t\npprint.pprint(processed_corpus)\n]" }, { "code": null, "e": 6935, "s": 6603, "text": "[['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time'],\n['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement'],\n['generation', 'random', 'binary', 'unordered', 'trees'],\n['intersection', 'graph', 'paths', 'trees'],\n['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering']]\n" }, { "code": null, "e": 7251, "s": 6935, "text": "Gensim also provides function for more effective preprocessing of the corpus. In such kind of preprocessing, we can convert a document into a list of lowercase tokens. We can also ignore tokens that are too short or too long. Such function is gensim.utils.simple_preprocess(doc, deacc=False, min_len=2, max_len=15)." }, { "code": null, "e": 7293, "s": 7251, "text": "gensim.utils.simple_preprocess() fucntion" }, { "code": null, "e": 7471, "s": 7293, "text": "Gensim provide this function to convert a document into a list of lowercase tokens and also for ignoring tokens that are too short or too long. It has the following parameters −" }, { "code": null, "e": 7545, "s": 7471, "text": "It refers to the input document on which preprocessing should be applied." }, { "code": null, "e": 7639, "s": 7545, "text": "This parameter is used to remove the accent marks from tokens. It uses deaccent() to do this." }, { "code": null, "e": 7772, "s": 7639, "text": "With the help of this parameter, we can set the minimum length of a token. The tokens shorter than defined length will be discarded." }, { "code": null, "e": 7903, "s": 7772, "text": "With the help of this parameter we can set the maximum length of a token. The tokens longer than defined length will be discarded." }, { "code": null, "e": 7982, "s": 7903, "text": "The output of this function would be the tokens extracted from input document." }, { "code": null, "e": 7989, "s": 7982, "text": " Print" }, { "code": null, "e": 8000, "s": 7989, "text": " Add Notes" } ]
Reshaping Pandas DataFrames. Melt, Stack and Pivot functions | by Soner Yıldırım | Towards Data Science
Pandas is a very powerful Python data analysis library that expedites the preprocessing steps of your project. The core data structure of Pandas is DataFrame which represents data in tabular form with labeled rows and columns. In this post, I will try to explain how to reshape a dataframe by modifying row-column structure. There are multiple ways to reshape a dataframe. We can choose the one that best fits the task at hand. The functions to reshape a dataframe: Melt Stack and unstack Pivot As always, we start with importing numpy and pandas: import pandas as pdimport numpy as np Melt is used to convert wide dataframes to narrow ones. What I mean by wide is a dataframe with a high number of columns. Some dataframes are structured in a way that consecutive measurements or variables are represented as columns. In some cases, representing these columns as rows may fit better to our task. Consider the following dataframe: df1 = pd.DataFrame({'city':['A','B','C'], 'day1':[22,25,28], 'day2':[10,14,13], 'day3':[25,22,26], 'day4':[18,15,17], 'day5':[12,14,18]}) We have three different cities and measurements done on different days. We decide to represent these days as rows in a column. There will also be a column to show the measurements. We can easily accomplish this by using melt function: df1.melt(id_vars=['city']) Variable and value column names are given by default. We can use var_name and value_name parameters of melt function to assign new column names. It will also look better if we sort the data by city column: df1.melt(id_vars=['city'], var_name = 'date', value_name = 'temperature').sort_values(by='city').reset_index(drop=True) Stack function kind of increases the index level of the dataframe. What I mean by increasing the level is: If dataframe has a simple column index, stack returns a series whose indices consist of row-column pairs of original dataframe. If dataframe has multi-level index, stack increases the index level. It is better explained with examples. Consider the following dataframe: df1 has 3 rows and 6 columns with simple integer column index. If stack function is applied to df1, it will return a series with 3 x 6 = 18 rows. The index of the series will be [(0, ‘city’), (0, ‘day1’), ... , (2, ‘day5’)]. Let’s also check the shape and index: df1.shape(3,6)df1.stack().shape(18,)df1.stack().index[0] #multilevel index(0, 'city') Stack and unstack functions are more commonly used for dataframes with multi-level indices. Let’s create a dataframe with multi-level index: tuples = [('A',1),('A',2),('A',3),('B',1),('A',2)]index = pd.MultiIndex.from_tuples(tuples, names=['first','second'])df2 = pd.DataFrame(np.random.randint(10, size=(5,2)), index=index, columns=['column_x', 'column_y']) If we apply stack function on this dataframe, the level of index will be increased: df_stacked = df2.stack().to_frame()df_stacked Now the names of the colums (column_x and column_y) are part of multi-level index. So the resulting dataframe has one column and a 3-level multi-index. len(df_stacked.index.levels)3len(df2.index.levels)2 Unstack is just the opposite of stack. If we apply unstack to the stacked dataframe, we will get back the original dataframe: df_stacked.unstack().indexMultiIndex(levels=[['A', 'B'], [1, 2, 3]], codes=[[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]], names=['first', 'second'])df2.indexMultiIndex(levels=[['A', 'B'], [1, 2, 3]], codes=[[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]], names=['first', 'second']) Pivot function can also be considered as a way to look at the dataframe from a different perspective. It is used to explore the relationships among variables by allowing to represent data in different formats. Consider the following dataframe: We want to see how values change according to city-name pairs. We can create a new representation of this dataframe with an index of names and columns of cities. If a city-name pair does not exist, corresponding cell is filled with NaN. We do not have to see all the values at once. The values to put in the dataframe can be filtered using values parameter: I think the success and prevalence of Pandas come from the versatile, powerful and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. Since a big portion of time spent on a data science project is spent during data cleaning and preprocessing steps, it is highly encouraged to learn Pandas. Thanks for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 497, "s": 172, "text": "Pandas is a very powerful Python data analysis library that expedites the preprocessing steps of your project. The core data structure of Pandas is DataFrame which represents data in tabular form with labeled rows and columns. In this post, I will try to explain how to reshape a dataframe by modifying row-column structure." }, { "code": null, "e": 638, "s": 497, "text": "There are multiple ways to reshape a dataframe. We can choose the one that best fits the task at hand. The functions to reshape a dataframe:" }, { "code": null, "e": 643, "s": 638, "text": "Melt" }, { "code": null, "e": 661, "s": 643, "text": "Stack and unstack" }, { "code": null, "e": 667, "s": 661, "text": "Pivot" }, { "code": null, "e": 720, "s": 667, "text": "As always, we start with importing numpy and pandas:" }, { "code": null, "e": 758, "s": 720, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 1069, "s": 758, "text": "Melt is used to convert wide dataframes to narrow ones. What I mean by wide is a dataframe with a high number of columns. Some dataframes are structured in a way that consecutive measurements or variables are represented as columns. In some cases, representing these columns as rows may fit better to our task." }, { "code": null, "e": 1103, "s": 1069, "text": "Consider the following dataframe:" }, { "code": null, "e": 1331, "s": 1103, "text": "df1 = pd.DataFrame({'city':['A','B','C'], 'day1':[22,25,28], 'day2':[10,14,13], 'day3':[25,22,26], 'day4':[18,15,17], 'day5':[12,14,18]})" }, { "code": null, "e": 1566, "s": 1331, "text": "We have three different cities and measurements done on different days. We decide to represent these days as rows in a column. There will also be a column to show the measurements. We can easily accomplish this by using melt function:" }, { "code": null, "e": 1593, "s": 1566, "text": "df1.melt(id_vars=['city'])" }, { "code": null, "e": 1799, "s": 1593, "text": "Variable and value column names are given by default. We can use var_name and value_name parameters of melt function to assign new column names. It will also look better if we sort the data by city column:" }, { "code": null, "e": 1919, "s": 1799, "text": "df1.melt(id_vars=['city'], var_name = 'date', value_name = 'temperature').sort_values(by='city').reset_index(drop=True)" }, { "code": null, "e": 2026, "s": 1919, "text": "Stack function kind of increases the index level of the dataframe. What I mean by increasing the level is:" }, { "code": null, "e": 2154, "s": 2026, "text": "If dataframe has a simple column index, stack returns a series whose indices consist of row-column pairs of original dataframe." }, { "code": null, "e": 2223, "s": 2154, "text": "If dataframe has multi-level index, stack increases the index level." }, { "code": null, "e": 2295, "s": 2223, "text": "It is better explained with examples. Consider the following dataframe:" }, { "code": null, "e": 2520, "s": 2295, "text": "df1 has 3 rows and 6 columns with simple integer column index. If stack function is applied to df1, it will return a series with 3 x 6 = 18 rows. The index of the series will be [(0, ‘city’), (0, ‘day1’), ... , (2, ‘day5’)]." }, { "code": null, "e": 2558, "s": 2520, "text": "Let’s also check the shape and index:" }, { "code": null, "e": 2644, "s": 2558, "text": "df1.shape(3,6)df1.stack().shape(18,)df1.stack().index[0] #multilevel index(0, 'city')" }, { "code": null, "e": 2785, "s": 2644, "text": "Stack and unstack functions are more commonly used for dataframes with multi-level indices. Let’s create a dataframe with multi-level index:" }, { "code": null, "e": 3022, "s": 2785, "text": "tuples = [('A',1),('A',2),('A',3),('B',1),('A',2)]index = pd.MultiIndex.from_tuples(tuples, names=['first','second'])df2 = pd.DataFrame(np.random.randint(10, size=(5,2)), index=index, columns=['column_x', 'column_y'])" }, { "code": null, "e": 3106, "s": 3022, "text": "If we apply stack function on this dataframe, the level of index will be increased:" }, { "code": null, "e": 3152, "s": 3106, "text": "df_stacked = df2.stack().to_frame()df_stacked" }, { "code": null, "e": 3304, "s": 3152, "text": "Now the names of the colums (column_x and column_y) are part of multi-level index. So the resulting dataframe has one column and a 3-level multi-index." }, { "code": null, "e": 3356, "s": 3304, "text": "len(df_stacked.index.levels)3len(df2.index.levels)2" }, { "code": null, "e": 3482, "s": 3356, "text": "Unstack is just the opposite of stack. If we apply unstack to the stacked dataframe, we will get back the original dataframe:" }, { "code": null, "e": 3780, "s": 3482, "text": "df_stacked.unstack().indexMultiIndex(levels=[['A', 'B'], [1, 2, 3]], codes=[[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]], names=['first', 'second'])df2.indexMultiIndex(levels=[['A', 'B'], [1, 2, 3]], codes=[[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]], names=['first', 'second'])" }, { "code": null, "e": 3990, "s": 3780, "text": "Pivot function can also be considered as a way to look at the dataframe from a different perspective. It is used to explore the relationships among variables by allowing to represent data in different formats." }, { "code": null, "e": 4024, "s": 3990, "text": "Consider the following dataframe:" }, { "code": null, "e": 4186, "s": 4024, "text": "We want to see how values change according to city-name pairs. We can create a new representation of this dataframe with an index of names and columns of cities." }, { "code": null, "e": 4261, "s": 4186, "text": "If a city-name pair does not exist, corresponding cell is filled with NaN." }, { "code": null, "e": 4382, "s": 4261, "text": "We do not have to see all the values at once. The values to put in the dataframe can be filtered using values parameter:" }, { "code": null, "e": 4739, "s": 4382, "text": "I think the success and prevalence of Pandas come from the versatile, powerful and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. Since a big portion of time spent on a data science project is spent during data cleaning and preprocessing steps, it is highly encouraged to learn Pandas." } ]
Machine Learning in Apache Spark for Beginners — Healthcare Data Analysis | by Sagar Daswani | Towards Data Science
Step by Step guide to build you first Machine Learning model in Apache Spark using Databricks Apache Spark is a cluster computing framework designed for fast and efficient computation. It can handle millions of data points with a relatively low amount of computing power. Apache Spark is built on top of and is an extension of Hadoop’s Map-Reduce, which efficiently uses different combinations of cluster computing. The main feature of Spark is in-memory cluster computing, which increases application speeds, including interactive queries and stream processing. This post is a quick-start guide for developing a prediction model in Spark using Databricks. I will be using a free community version from Databricks, credits to them! In this post, I will be using machine learning to help us predict the probability of a patient having diabetes. The dataset is downloaded from the UCI Machine Learning Repository. Here I am predicting diabetes probability using the information provided about the patient. It is a binary classification problem, where I will try to predict the probability of an observation belonging to a diabetes category. I am going to first demonstrate a minimum amount of exploratory analysis and later will jump to machine learning models (i.e., regression and tree-based models) and will compare and summarize the results. The following code lines load the data and create a dataframe object. Setting Inferschema to true can give a good guess about the data type of each column. #The Applied options are for CSV filesdf = spark.read.format("csv") \ .option("inferSchema","true") \ .option("header","true") \ .option("sep",",") \ .load(file_location) I also created a dictionary to store features with respect to their data types. In our case, we have an ‘Integer Type’ and ‘Double Type’. from collections import defaultdictdata_types = defaultdict(list)for entry in df.schema.fields: data_types[str(entry.dataType)].append(entry.name) Let’s have a look at the first 5 rows of our dataset. display(df.limit(5)) The diabetes dataset consists of 768 data points with 9 features each: “Outcome” is the feature we are going to predict, where 0 means the patient does not have diabetes, and 1 means the patient does have diabetes. Of these 768 data points, 500 are labeled as 0 and 268 as 1. display(df.groupby('Outcome').count()) One advantage of using Databricks is it helps one to visualize the query into some basic plot options to provides a better understanding of data along with code. We have a complete dataset without any missing values, but to find more information about dealing with missing data, you can consult this article: https://www.analyticsvidhya.com/blog/tag/missing-values-treatment/ In our data, we only have a single categorical column, i.e., ‘Pregnancies’ with over 17 categories. The following code shows how you can convert categorical columns/features into one-hot encoding. In Spark, ‘String Indexer’ is used which assigns a unique integer value to each category. 0 is assigned to the most frequent category, 1 to the next most frequent category, and so on. from pyspark.ml import Pipelinefrom pyspark.ml.feature import OneHotEncoder, StringIndexerstage_string = [StringIndexer(inputCol= c, outputCol= c+"_string_encoded") for c in strings_used]stage_one_hot = [OneHotEncoder(inputCol= c+"_string_encoded", outputCol= c+ "_one_hot") for c in strings_used]ppl = Pipeline(stages= stage_string + stage_one_hot)df = ppl.fit(df).transform(df) In the above code, I have used a pipeline that effectively deals with a series of tasks in a single iteration. One can make a list of tasks and a pipeline will handle everything. In general, a machine learning pipeline describes the process of writing code, releasing it to production, doing data extraction, creating training models and tuning the algorithm. It is a continuous process while working on an ML platform. But when it comes to Apache Spark a pipeline is an object that transforms, evaluates, and fits steps into one object. These steps are called ml workflow. The idea here is to assemble a given list of columns into a single vector column and bundle them together. This is an additional step that is required by Spark’s machine learning models. This step is usually performed at the end of data exploration and pre-processing steps. At this stage, I am working with a few raw and few transformed features that can be used to train a model. from pyspark.ml.feature import VectorAssemblerfeatures = ['Pregnancies_one_hot','Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']vector_assembler = VectorAssembler(inputCols = features, outputCol= "features")data_training_and_test = vector_assembler.transform(df) We have a couple of built-in classifiers, including random forest, boosting trees, logistic regression, etc. To start with, I am implementing Random Forest as an example, specifying the number of trees in the classifier and leaving the remaining parameters at their default value. To evaluate the performance of our model, I am using the ROC curve metric. You can choose ‘metricName’ of your choice. The accuracy of this model is 82.5%. This indicates our model is working quite well with the default parameters. from pyspark.ml.classification import RandomForestClassifierfrom pyspark.ml.evaluation import BinaryClassificationEvaluator(training_data, test_data) = data_training_and_test.randomSplit([0.7, 0.3], 2017)rf = RandomForestClassifier(labelCol = "Outcome", featuresCol = "features", numTrees = 20)rf_model = rf.fit(training_data)predictions = rf_model.transform(test_data)evaluator= BinaryClassificationEvaluator(labelCol = "Outcome", rawPredictionCol="probability", metricName= "areaUnderROC")accuracy = evaluator.evaluate(predictions)print("Accuracy:",accuracy*100) The feature selection process helps to filter out less important variables that can lead to a simpler and more stable model. In Spark, implementing feature selection is not as easy as in, for example, Python’s scikit-learn, but it can be managed by making feature selection part of the pipeline. The idea is: Fit the classifier first. For instance, you can go with the regression or tree-based models, any model of your choice.Find feature importance if you use the random forest, find the coefficient if you are using logistic regression.Store the most important set of features in a list.Use the ‘VectorSlicer’ method from the ml library, and make a new vector from the list you just selected. Fit the classifier first. For instance, you can go with the regression or tree-based models, any model of your choice. Find feature importance if you use the random forest, find the coefficient if you are using logistic regression. Store the most important set of features in a list. Use the ‘VectorSlicer’ method from the ml library, and make a new vector from the list you just selected. The following code shows how to create a list of important features, from the model that we previously fitted. Features greater than 0.03 are kept, rf_model is the fitted random forest model. importance_list = pd.Series(rf_model.featureImportances.values)sorted_imp = importance_list.sort_values(ascending= False)kept = list((sorted_imp[sorted_imp > 0.03]).index) Taking 0.03 is random, one can try different values based on the AUC metric. Later I used vector slicer to collect all features that have importance greater than 0.03. from pyspark.ml.feature import VectorSlicervector_slicer = VectorSlicer(inputCol= "features", indices= kept, outputCol= "feature_subset")with_selected_feature = vector_slicer.transform(training_data)rf_modified = RandomForestClassifier(numTrees=20, labelCol = "Outcome", featuresCol="feature_subset")test_data = vector_slicer.transform(test_data)prediction_modified = rf_modified.fit(with_selected_feature) .transform(test_data)evaluator_modified = BinaryClassificationEvaluator(labelCol = "Outcome",rawPredictionCol="probability", metricName= "areaUnderROC")accuracy = evaluator_modified.evaluate(prediction_modified)print("Accuracy: ",accuracy*100) With feature selection, we saw an improvement of 1% in the accuracy with overall accuracy as 83%. From the full feature set, we got 82% accuracy. When dealing with big data even 1% improvement matters. In the end, I just want to conclude by saying that Apache Spark is concise and easy to use an open-source framework. Thank you for taking the time to read! I am always looking forward to learn and grow, reach out to me if you have any questions or suggestions! LinkedIn | [email protected] | Github
[ { "code": null, "e": 265, "s": 171, "text": "Step by Step guide to build you first Machine Learning model in Apache Spark using Databricks" }, { "code": null, "e": 734, "s": 265, "text": "Apache Spark is a cluster computing framework designed for fast and efficient computation. It can handle millions of data points with a relatively low amount of computing power. Apache Spark is built on top of and is an extension of Hadoop’s Map-Reduce, which efficiently uses different combinations of cluster computing. The main feature of Spark is in-memory cluster computing, which increases application speeds, including interactive queries and stream processing." }, { "code": null, "e": 828, "s": 734, "text": "This post is a quick-start guide for developing a prediction model in Spark using Databricks." }, { "code": null, "e": 903, "s": 828, "text": "I will be using a free community version from Databricks, credits to them!" }, { "code": null, "e": 1083, "s": 903, "text": "In this post, I will be using machine learning to help us predict the probability of a patient having diabetes. The dataset is downloaded from the UCI Machine Learning Repository." }, { "code": null, "e": 1310, "s": 1083, "text": "Here I am predicting diabetes probability using the information provided about the patient. It is a binary classification problem, where I will try to predict the probability of an observation belonging to a diabetes category." }, { "code": null, "e": 1515, "s": 1310, "text": "I am going to first demonstrate a minimum amount of exploratory analysis and later will jump to machine learning models (i.e., regression and tree-based models) and will compare and summarize the results." }, { "code": null, "e": 1671, "s": 1515, "text": "The following code lines load the data and create a dataframe object. Setting Inferschema to true can give a good guess about the data type of each column." }, { "code": null, "e": 1858, "s": 1671, "text": "#The Applied options are for CSV filesdf = spark.read.format(\"csv\") \\ .option(\"inferSchema\",\"true\") \\ .option(\"header\",\"true\") \\ .option(\"sep\",\",\") \\ .load(file_location)" }, { "code": null, "e": 1996, "s": 1858, "text": "I also created a dictionary to store features with respect to their data types. In our case, we have an ‘Integer Type’ and ‘Double Type’." }, { "code": null, "e": 2144, "s": 1996, "text": "from collections import defaultdictdata_types = defaultdict(list)for entry in df.schema.fields: data_types[str(entry.dataType)].append(entry.name)" }, { "code": null, "e": 2198, "s": 2144, "text": "Let’s have a look at the first 5 rows of our dataset." }, { "code": null, "e": 2219, "s": 2198, "text": "display(df.limit(5))" }, { "code": null, "e": 2290, "s": 2219, "text": "The diabetes dataset consists of 768 data points with 9 features each:" }, { "code": null, "e": 2495, "s": 2290, "text": "“Outcome” is the feature we are going to predict, where 0 means the patient does not have diabetes, and 1 means the patient does have diabetes. Of these 768 data points, 500 are labeled as 0 and 268 as 1." }, { "code": null, "e": 2534, "s": 2495, "text": "display(df.groupby('Outcome').count())" }, { "code": null, "e": 2696, "s": 2534, "text": "One advantage of using Databricks is it helps one to visualize the query into some basic plot options to provides a better understanding of data along with code." }, { "code": null, "e": 2843, "s": 2696, "text": "We have a complete dataset without any missing values, but to find more information about dealing with missing data, you can consult this article:" }, { "code": null, "e": 2910, "s": 2843, "text": "https://www.analyticsvidhya.com/blog/tag/missing-values-treatment/" }, { "code": null, "e": 3291, "s": 2910, "text": "In our data, we only have a single categorical column, i.e., ‘Pregnancies’ with over 17 categories. The following code shows how you can convert categorical columns/features into one-hot encoding. In Spark, ‘String Indexer’ is used which assigns a unique integer value to each category. 0 is assigned to the most frequent category, 1 to the next most frequent category, and so on." }, { "code": null, "e": 3685, "s": 3291, "text": "from pyspark.ml import Pipelinefrom pyspark.ml.feature import OneHotEncoder, StringIndexerstage_string = [StringIndexer(inputCol= c, outputCol= c+\"_string_encoded\") for c in strings_used]stage_one_hot = [OneHotEncoder(inputCol= c+\"_string_encoded\", outputCol= c+ \"_one_hot\") for c in strings_used]ppl = Pipeline(stages= stage_string + stage_one_hot)df = ppl.fit(df).transform(df)" }, { "code": null, "e": 3864, "s": 3685, "text": "In the above code, I have used a pipeline that effectively deals with a series of tasks in a single iteration. One can make a list of tasks and a pipeline will handle everything." }, { "code": null, "e": 4259, "s": 3864, "text": "In general, a machine learning pipeline describes the process of writing code, releasing it to production, doing data extraction, creating training models and tuning the algorithm. It is a continuous process while working on an ML platform. But when it comes to Apache Spark a pipeline is an object that transforms, evaluates, and fits steps into one object. These steps are called ml workflow." }, { "code": null, "e": 4641, "s": 4259, "text": "The idea here is to assemble a given list of columns into a single vector column and bundle them together. This is an additional step that is required by Spark’s machine learning models. This step is usually performed at the end of data exploration and pre-processing steps. At this stage, I am working with a few raw and few transformed features that can be used to train a model." }, { "code": null, "e": 4982, "s": 4641, "text": "from pyspark.ml.feature import VectorAssemblerfeatures = ['Pregnancies_one_hot','Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']vector_assembler = VectorAssembler(inputCols = features, outputCol= \"features\")data_training_and_test = vector_assembler.transform(df)" }, { "code": null, "e": 5263, "s": 4982, "text": "We have a couple of built-in classifiers, including random forest, boosting trees, logistic regression, etc. To start with, I am implementing Random Forest as an example, specifying the number of trees in the classifier and leaving the remaining parameters at their default value." }, { "code": null, "e": 5382, "s": 5263, "text": "To evaluate the performance of our model, I am using the ROC curve metric. You can choose ‘metricName’ of your choice." }, { "code": null, "e": 5495, "s": 5382, "text": "The accuracy of this model is 82.5%. This indicates our model is working quite well with the default parameters." }, { "code": null, "e": 6084, "s": 5495, "text": "from pyspark.ml.classification import RandomForestClassifierfrom pyspark.ml.evaluation import BinaryClassificationEvaluator(training_data, test_data) = data_training_and_test.randomSplit([0.7, 0.3], 2017)rf = RandomForestClassifier(labelCol = \"Outcome\", featuresCol = \"features\", numTrees = 20)rf_model = rf.fit(training_data)predictions = rf_model.transform(test_data)evaluator= BinaryClassificationEvaluator(labelCol = \"Outcome\", rawPredictionCol=\"probability\", metricName= \"areaUnderROC\")accuracy = evaluator.evaluate(predictions)print(\"Accuracy:\",accuracy*100)" }, { "code": null, "e": 6393, "s": 6084, "text": "The feature selection process helps to filter out less important variables that can lead to a simpler and more stable model. In Spark, implementing feature selection is not as easy as in, for example, Python’s scikit-learn, but it can be managed by making feature selection part of the pipeline. The idea is:" }, { "code": null, "e": 6780, "s": 6393, "text": "Fit the classifier first. For instance, you can go with the regression or tree-based models, any model of your choice.Find feature importance if you use the random forest, find the coefficient if you are using logistic regression.Store the most important set of features in a list.Use the ‘VectorSlicer’ method from the ml library, and make a new vector from the list you just selected." }, { "code": null, "e": 6899, "s": 6780, "text": "Fit the classifier first. For instance, you can go with the regression or tree-based models, any model of your choice." }, { "code": null, "e": 7012, "s": 6899, "text": "Find feature importance if you use the random forest, find the coefficient if you are using logistic regression." }, { "code": null, "e": 7064, "s": 7012, "text": "Store the most important set of features in a list." }, { "code": null, "e": 7170, "s": 7064, "text": "Use the ‘VectorSlicer’ method from the ml library, and make a new vector from the list you just selected." }, { "code": null, "e": 7362, "s": 7170, "text": "The following code shows how to create a list of important features, from the model that we previously fitted. Features greater than 0.03 are kept, rf_model is the fitted random forest model." }, { "code": null, "e": 7534, "s": 7362, "text": "importance_list = pd.Series(rf_model.featureImportances.values)sorted_imp = importance_list.sort_values(ascending= False)kept = list((sorted_imp[sorted_imp > 0.03]).index)" }, { "code": null, "e": 7702, "s": 7534, "text": "Taking 0.03 is random, one can try different values based on the AUC metric. Later I used vector slicer to collect all features that have importance greater than 0.03." }, { "code": null, "e": 8425, "s": 7702, "text": "from pyspark.ml.feature import VectorSlicervector_slicer = VectorSlicer(inputCol= \"features\", indices= kept, outputCol= \"feature_subset\")with_selected_feature = vector_slicer.transform(training_data)rf_modified = RandomForestClassifier(numTrees=20, labelCol = \"Outcome\", featuresCol=\"feature_subset\")test_data = vector_slicer.transform(test_data)prediction_modified = rf_modified.fit(with_selected_feature) .transform(test_data)evaluator_modified = BinaryClassificationEvaluator(labelCol = \"Outcome\",rawPredictionCol=\"probability\", metricName= \"areaUnderROC\")accuracy = evaluator_modified.evaluate(prediction_modified)print(\"Accuracy: \",accuracy*100)" }, { "code": null, "e": 8627, "s": 8425, "text": "With feature selection, we saw an improvement of 1% in the accuracy with overall accuracy as 83%. From the full feature set, we got 82% accuracy. When dealing with big data even 1% improvement matters." }, { "code": null, "e": 8744, "s": 8627, "text": "In the end, I just want to conclude by saying that Apache Spark is concise and easy to use an open-source framework." }, { "code": null, "e": 8783, "s": 8744, "text": "Thank you for taking the time to read!" }, { "code": null, "e": 8888, "s": 8783, "text": "I am always looking forward to learn and grow, reach out to me if you have any questions or suggestions!" } ]
Boyer Moore Algorithm | Good Suffix heuristic - GeeksforGeeks
31 Oct, 2019 We have already discussed Bad character heuristic variation of Boyer Moore algorithm. In this article we will discuss Good Suffix heuristic for pattern searching. Just like bad character heuristic, a preprocessing table is generated for good suffix heuristic. Good Suffix Heuristic Let t be substring of text T which is matched with substring of pattern P. Now we shift pattern until :1) Another occurrence of t in P matched with t in T.2) A prefix of P, which matches with suffix of t3) P moves past t Case 1: Another occurrence of t in P matched with t in TPattern P might contain few more occurrences of t. In such case, we will try to shift the pattern to align that occurrence with t in text T. For example- Explanation: In the above example, we have got a substring t of text T matched with pattern P (in green) before mismatch at index 2. Now we will search for occurrence of t (“AB”) in P. We have found an occurrence starting at position 1 (in yellow background) so we will right shift the pattern 2 times to align t in P with t in T. This is weak rule of original Boyer Moore and not much effective, we will discuss a Strong Good Suffix rule shortly. Case 2: A prefix of P, which matches with suffix of t in TIt is not always likely that we will find the occurrence of t in P. Sometimes there is no occurrence at all, in such cases sometimes we can search for some suffix of t matching with some prefix of P and try to align them by shifting P. For example – Explanation: In above example, we have got t (“BAB”) matched with P (in green) at index 2-4 before mismatch . But because there exists no occurrence of t in P we will search for some prefix of P which matches with some suffix of t. We have found prefix “AB” (in the yellow background) starting at index 0 which matches not with whole t but the suffix of t “AB” starting at index 3. So now we will shift pattern 3 times to align prefix with the suffix. Case 3: P moves past tIf the above two cases are not satisfied, we will shift the pattern past the t. For example – Explanation: If above example, there exist no occurrence of t (“AB”) in P and also there is no prefix in P which matches with the suffix of t. So, in that case, we can never find any perfect match before index 4, so we will shift the P past the t ie. to index 5. Strong Good suffix Heuristic Suppose substring q = P[i to n] got matched with t in T and c = P[i-1] is the mismatching character. Now unlike case 1 we will search for t in P which is not preceded by character c. The closest such occurrence is then aligned with t in T by shifting pattern P. For example – Explanation: In above example, q = P[7 to 8] got matched with t in T. The mismatching character c is “C” at position P[6]. Now if we start searching t in P we will get the first occurrence of t starting at position 4. But this occurrence is preceded by “C” which is equal to c, so we will skip this and carry on searching. At position 1 we got another occurrence of t (in the yellow background). This occurrence is preceded by “A” (in blue) which is not equivalent to c. So we will shift pattern P 6 times to align this occurrence with t in T.We are doing this because we already know that character c = “C” causes the mismatch. So any occurrence of t preceded by c will again cause mismatch when aligned with t, so that’s why it is better to skip this. Preprocessing for Good suffix heuristic As a part of preprocessing, an array shift is created. Each entry shift[i] contain the distance pattern will shift if mismatch occur at position i-1. That is, the suffix of pattern starting at position i is matched and a mismatch occur at position i-1. Preprocessing is done separately for strong good suffix and case 2 discussed above. 1) Preprocessing for Strong Good SuffixBefore discussing preprocessing, let us first discuss the idea of border. A border is a substring which is both proper suffix and proper prefix. For example, in string “ccacc”, “c” is a border, “cc” is a border because it appears in both end of string but “cca” is not a border. As a part of preprocessing an array bpos (border position) is calculated. Each entry bpos[i] contains the starting index of border for suffix starting at index i in given pattern P.The suffix φ beginning at position m has no border, so bpos[m] is set to m+1 where m is the length of the pattern.The shift position is obtained by the borders which cannot be extended to the left. Following is the code for preprocessing – void preprocess_strong_suffix(int *shift, int *bpos, char *pat, int m) { int i = m, j = m+1; bpos[i] = j; while(i > 0) { while(j <= m && pat[i-1] != pat[j-1]) { if (shift[j] == 0) shift[j] = j-i; j = bpos[j]; } i--; j--; bpos[i] = j; } } Explanation: Consider pattern P = “ABBABAB”, m = 7. The widest border of suffix “AB” beginning at position i = 5 is φ(nothing) starting at position 7 so bpos[5] = 7. At position i = 2 the suffix is “BABAB”. The widest border for this suffix is “BAB” starting at position 4, so j = bpos[2] = 4.We can understand bpos[i] = j using following example –If character # Which is at position i-1 is equivalent to character ? at position j-1, we know that border will be ? + border of suffix at position i which is starting at position j which is equivalent to saying that border of suffix at i-1 begin at j-1 or bpos[ i-1 ] = j-1 or in the code –i--; j--; bpos[ i ] = j But if character # at position i-1 do not match with character ? at position j-1 then we continue our search to the right. Now we know that –Border width will be smaller than the border starting at position j ie. smaller than x...φBorder has to begin with # and end with φ or could be empty (no border exist).With above two facts we will continue our search in sub string x...φ from position j to m. The next border should be at j = bpos[j]. After updating j, we again compare character at position j-1 (?) with # and if they are equal then we got our border otherwise we continue our search to right until j>m. This process is shown by code –while(j <= m && pat[i-1] != pat[j-1]) { j = bpos[j]; } i--; j--; bpos[i]=j; In above code look at these conditions –pat[i-1] != pat[j-1] This is the condition which we discussed in case 2. When the character preceding the occurrence of t in pattern P is different than mismatching character in P, we stop skipping the occurrences and shift the pattern. So here P[i] == P[j] but P[i-1] != p[j-1] so we shift pattern from i to j. So shift[j] = j-i is recorder for j. So whenever any mismatch occur at position j we will shift the pattern shift[j+1] positions to the right.In above code the following condition is very important –if (shift[j] == 0 ) This condition prevent modification of shift[j] value from suffix having same border. For example, Consider pattern P = “addbddcdd”, when we calculate bpos[ i-1 ] for i = 4 then j = 7 in this case. we will be eventually setting value of shift[ 7 ] = 3. Now if we calculate bpos[ i-1 ] for i = 1 then j = 7 and we will be setting value shift[ 7 ] = 6 again if there is no test shift[ j ] == 0. This mean if we have a mismatch at position 6 we will shift pattern P 3 positions to right not 6 position.2) Preprocessing for Case 2In the preprocessing for case 2, for each suffix the widest border of the whole pattern that is contained in that suffix is determined.The starting position of the widest border of the pattern at all is stored in bpos[0]In the following preprocessing algorithm, this value bpos[0] is stored initially in all free entries of array shift. But when the suffix of the pattern becomes shorter than bpos[0], the algorithm continues with the next-wider border of the pattern, i.e. with bpos[j].Following is the implementation of the search algorithm –C++JavaPython3C#C++/* C program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string */ #include <stdio.h>#include <string.h> // preprocessing for strong good suffix rulevoid preprocess_strong_suffix(int *shift, int *bpos, char *pat, int m){ // m is the length of pattern int i=m, j=m+1; bpos[i]=j; while(i>0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j<=m && pat[i-1] != pat[j-1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j]==0) shift[j] = j-i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--;j--; bpos[i] = j; }} //Preprocessing for case 2void preprocess_case2(int *shift, int *bpos, char *pat, int m){ int i, j; j = bpos[0]; for(i=0; i<=m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i]==0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i==j) j = bpos[j]; }} /*Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule */void search(char *text, char *pat){ // s is shift of the pattern with respect to text int s=0, j; int m = strlen(pat); int n = strlen(text); int bpos[m+1], shift[m+1]; //initialize all occurrence of shift to 0 for(int i=0;i<m+1;i++) shift[i]=0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n-m) { j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j<0) { printf("pattern occurs at shift = %d\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j+1]; } } //Driver int main(){ char text[] = "ABAAAABAACD"; char pat[] = "ABA"; search(text, pat); return 0;}Java/* Java program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.length; int n = text.length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; //initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.printf("pattern occurs at shift = %d\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; } } // Driver Codepublic static void main(String[] args) { char []text = "ABAAAABAACD".toCharArray(); char []pat = "ABA".toCharArray(); search(text, pat);}} // This code is contributed by 29AjayKumarPython3# Python3 program for Boyer Moore Algorithm with # Good Suffix heuristic to find pattern in # given text string # preprocessing for strong good suffix ruledef preprocess_strong_suffix(shift, bpos, pat, m): # m is the length of pattern i = m j = m + 1 bpos[i] = j while i > 0: '''if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border ''' while j <= m and pat[i - 1] != pat[j - 1]: ''' the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j ''' if shift[j] == 0: shift[j] = j - i # Update the position of next border j = bpos[j] ''' p[i-1] matched with p[j-1], border is found. store the beginning position of border ''' i -= 1 j -= 1 bpos[i] = j # Preprocessing for case 2def preprocess_case2(shift, bpos, pat, m): j = bpos[0] for i in range(m + 1): ''' set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 ''' if shift[i] == 0: shift[i] = j ''' suffix becomes shorter than bpos[0], use the position of next widest border as value of j ''' if i == j: j = bpos[j] '''Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule '''def search(text, pat): # s is shift of the pattern with respect to text s = 0 m = len(pat) n = len(text) bpos = [0] * (m + 1) # initialize all occurrence of shift to 0 shift = [0] * (m + 1) # do preprocessing preprocess_strong_suffix(shift, bpos, pat, m) preprocess_case2(shift, bpos, pat, m) while s <= n - m: j = m - 1 ''' Keep reducing index j of pattern while characters of pattern and text are matching at this shift s''' while j >= 0 and pat[j] == text[s + j]: j -= 1 ''' If the pattern is present at the current shift, then index j will become -1 after the above loop ''' if j < 0: print("pattern occurs at shift = %d" % s) s += shift[0] else: '''pat[i] != pat[s+j] so shift the pattern shift[j+1] times ''' s += shift[j + 1] # Driver Codeif __name__ == "__main__": text = "ABAAAABAACD" pat = "ABA" search(text, pat) # This code is contributed by# sanjeev2552C#/* C# program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */using System; class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.Length; int n = text.Length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; // initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; // do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s + j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.Write("pattern occurs at shift = {0}\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; }} // Driver Codepublic static void Main(String[] args) { char []text = "ABAAAABAACD".ToCharArray(); char []pat = "ABA".ToCharArray(); search(text, pat);}} // This code is contributed by PrinciRaj1992Output:pattern occurs at shift = 0 pattern occurs at shift = 5 Referenceshttp://www.iti.fh-flensburg.de/lang/algorithmen/pattern/bmen.htmThis article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave We can understand bpos[i] = j using following example – If character # Which is at position i-1 is equivalent to character ? at position j-1, we know that border will be ? + border of suffix at position i which is starting at position j which is equivalent to saying that border of suffix at i-1 begin at j-1 or bpos[ i-1 ] = j-1 or in the code – i--; j--; bpos[ i ] = j But if character # at position i-1 do not match with character ? at position j-1 then we continue our search to the right. Now we know that – Border width will be smaller than the border starting at position j ie. smaller than x...φBorder has to begin with # and end with φ or could be empty (no border exist). Border width will be smaller than the border starting at position j ie. smaller than x...φ Border has to begin with # and end with φ or could be empty (no border exist). With above two facts we will continue our search in sub string x...φ from position j to m. The next border should be at j = bpos[j]. After updating j, we again compare character at position j-1 (?) with # and if they are equal then we got our border otherwise we continue our search to right until j>m. This process is shown by code – while(j <= m && pat[i-1] != pat[j-1]) { j = bpos[j]; } i--; j--; bpos[i]=j; In above code look at these conditions – pat[i-1] != pat[j-1] This is the condition which we discussed in case 2. When the character preceding the occurrence of t in pattern P is different than mismatching character in P, we stop skipping the occurrences and shift the pattern. So here P[i] == P[j] but P[i-1] != p[j-1] so we shift pattern from i to j. So shift[j] = j-i is recorder for j. So whenever any mismatch occur at position j we will shift the pattern shift[j+1] positions to the right.In above code the following condition is very important – if (shift[j] == 0 ) This condition prevent modification of shift[j] value from suffix having same border. For example, Consider pattern P = “addbddcdd”, when we calculate bpos[ i-1 ] for i = 4 then j = 7 in this case. we will be eventually setting value of shift[ 7 ] = 3. Now if we calculate bpos[ i-1 ] for i = 1 then j = 7 and we will be setting value shift[ 7 ] = 6 again if there is no test shift[ j ] == 0. This mean if we have a mismatch at position 6 we will shift pattern P 3 positions to right not 6 position. 2) Preprocessing for Case 2In the preprocessing for case 2, for each suffix the widest border of the whole pattern that is contained in that suffix is determined.The starting position of the widest border of the pattern at all is stored in bpos[0]In the following preprocessing algorithm, this value bpos[0] is stored initially in all free entries of array shift. But when the suffix of the pattern becomes shorter than bpos[0], the algorithm continues with the next-wider border of the pattern, i.e. with bpos[j]. Following is the implementation of the search algorithm – C++ Java Python3 C# /* C program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string */ #include <stdio.h>#include <string.h> // preprocessing for strong good suffix rulevoid preprocess_strong_suffix(int *shift, int *bpos, char *pat, int m){ // m is the length of pattern int i=m, j=m+1; bpos[i]=j; while(i>0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j<=m && pat[i-1] != pat[j-1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j]==0) shift[j] = j-i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--;j--; bpos[i] = j; }} //Preprocessing for case 2void preprocess_case2(int *shift, int *bpos, char *pat, int m){ int i, j; j = bpos[0]; for(i=0; i<=m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i]==0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i==j) j = bpos[j]; }} /*Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule */void search(char *text, char *pat){ // s is shift of the pattern with respect to text int s=0, j; int m = strlen(pat); int n = strlen(text); int bpos[m+1], shift[m+1]; //initialize all occurrence of shift to 0 for(int i=0;i<m+1;i++) shift[i]=0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n-m) { j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j<0) { printf("pattern occurs at shift = %d\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j+1]; } } //Driver int main(){ char text[] = "ABAAAABAACD"; char pat[] = "ABA"; search(text, pat); return 0;} /* Java program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.length; int n = text.length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; //initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.printf("pattern occurs at shift = %d\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; } } // Driver Codepublic static void main(String[] args) { char []text = "ABAAAABAACD".toCharArray(); char []pat = "ABA".toCharArray(); search(text, pat);}} // This code is contributed by 29AjayKumar # Python3 program for Boyer Moore Algorithm with # Good Suffix heuristic to find pattern in # given text string # preprocessing for strong good suffix ruledef preprocess_strong_suffix(shift, bpos, pat, m): # m is the length of pattern i = m j = m + 1 bpos[i] = j while i > 0: '''if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border ''' while j <= m and pat[i - 1] != pat[j - 1]: ''' the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j ''' if shift[j] == 0: shift[j] = j - i # Update the position of next border j = bpos[j] ''' p[i-1] matched with p[j-1], border is found. store the beginning position of border ''' i -= 1 j -= 1 bpos[i] = j # Preprocessing for case 2def preprocess_case2(shift, bpos, pat, m): j = bpos[0] for i in range(m + 1): ''' set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 ''' if shift[i] == 0: shift[i] = j ''' suffix becomes shorter than bpos[0], use the position of next widest border as value of j ''' if i == j: j = bpos[j] '''Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule '''def search(text, pat): # s is shift of the pattern with respect to text s = 0 m = len(pat) n = len(text) bpos = [0] * (m + 1) # initialize all occurrence of shift to 0 shift = [0] * (m + 1) # do preprocessing preprocess_strong_suffix(shift, bpos, pat, m) preprocess_case2(shift, bpos, pat, m) while s <= n - m: j = m - 1 ''' Keep reducing index j of pattern while characters of pattern and text are matching at this shift s''' while j >= 0 and pat[j] == text[s + j]: j -= 1 ''' If the pattern is present at the current shift, then index j will become -1 after the above loop ''' if j < 0: print("pattern occurs at shift = %d" % s) s += shift[0] else: '''pat[i] != pat[s+j] so shift the pattern shift[j+1] times ''' s += shift[j + 1] # Driver Codeif __name__ == "__main__": text = "ABAAAABAACD" pat = "ABA" search(text, pat) # This code is contributed by# sanjeev2552 /* C# program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */using System; class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.Length; int n = text.Length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; // initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; // do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s + j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.Write("pattern occurs at shift = {0}\n", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; }} // Driver Codepublic static void Main(String[] args) { char []text = "ABAAAABAACD".ToCharArray(); char []pat = "ABA".ToCharArray(); search(text, pat);}} // This code is contributed by PrinciRaj1992 pattern occurs at shift = 0 pattern occurs at shift = 5 References http://www.iti.fh-flensburg.de/lang/algorithmen/pattern/bmen.htm This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Kirti_Mangal nidhi_biet 29AjayKumar princiraj1992 sanjeev2552 Pattern Searching Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count N-length strings consisting only of vowels sorted lexicographically Check if a string contains uppercase, lowercase, special characters and numeric values Suffix Array | Set 1 (Introduction) Applications of String Matching Algorithms Remove leading zeros from a Number given as a string How to validate a domain name using Regular Expression Pattern Searching using Suffix Tree Split the binary string into substrings with equal number of 0s and 1s Check if a string consists only of special characters How to validate PAN Card number using Regular Expression
[ { "code": null, "e": 24936, "s": 24908, "text": "\n31 Oct, 2019" }, { "code": null, "e": 25196, "s": 24936, "text": "We have already discussed Bad character heuristic variation of Boyer Moore algorithm. In this article we will discuss Good Suffix heuristic for pattern searching. Just like bad character heuristic, a preprocessing table is generated for good suffix heuristic." }, { "code": null, "e": 25218, "s": 25196, "text": "Good Suffix Heuristic" }, { "code": null, "e": 25439, "s": 25218, "text": "Let t be substring of text T which is matched with substring of pattern P. Now we shift pattern until :1) Another occurrence of t in P matched with t in T.2) A prefix of P, which matches with suffix of t3) P moves past t" }, { "code": null, "e": 25649, "s": 25439, "text": "Case 1: Another occurrence of t in P matched with t in TPattern P might contain few more occurrences of t. In such case, we will try to shift the pattern to align that occurrence with t in text T. For example-" }, { "code": null, "e": 26097, "s": 25649, "text": "Explanation: In the above example, we have got a substring t of text T matched with pattern P (in green) before mismatch at index 2. Now we will search for occurrence of t (“AB”) in P. We have found an occurrence starting at position 1 (in yellow background) so we will right shift the pattern 2 times to align t in P with t in T. This is weak rule of original Boyer Moore and not much effective, we will discuss a Strong Good Suffix rule shortly." }, { "code": null, "e": 26405, "s": 26097, "text": "Case 2: A prefix of P, which matches with suffix of t in TIt is not always likely that we will find the occurrence of t in P. Sometimes there is no occurrence at all, in such cases sometimes we can search for some suffix of t matching with some prefix of P and try to align them by shifting P. For example –" }, { "code": null, "e": 26857, "s": 26405, "text": "Explanation: In above example, we have got t (“BAB”) matched with P (in green) at index 2-4 before mismatch . But because there exists no occurrence of t in P we will search for some prefix of P which matches with some suffix of t. We have found prefix “AB” (in the yellow background) starting at index 0 which matches not with whole t but the suffix of t “AB” starting at index 3. So now we will shift pattern 3 times to align prefix with the suffix." }, { "code": null, "e": 26973, "s": 26857, "text": "Case 3: P moves past tIf the above two cases are not satisfied, we will shift the pattern past the t. For example –" }, { "code": null, "e": 27236, "s": 26973, "text": "Explanation: If above example, there exist no occurrence of t (“AB”) in P and also there is no prefix in P which matches with the suffix of t. So, in that case, we can never find any perfect match before index 4, so we will shift the P past the t ie. to index 5." }, { "code": null, "e": 27265, "s": 27236, "text": "Strong Good suffix Heuristic" }, { "code": null, "e": 27541, "s": 27265, "text": "Suppose substring q = P[i to n] got matched with t in T and c = P[i-1] is the mismatching character. Now unlike case 1 we will search for t in P which is not preceded by character c. The closest such occurrence is then aligned with t in T by shifting pattern P. For example –" }, { "code": null, "e": 28295, "s": 27541, "text": "Explanation: In above example, q = P[7 to 8] got matched with t in T. The mismatching character c is “C” at position P[6]. Now if we start searching t in P we will get the first occurrence of t starting at position 4. But this occurrence is preceded by “C” which is equal to c, so we will skip this and carry on searching. At position 1 we got another occurrence of t (in the yellow background). This occurrence is preceded by “A” (in blue) which is not equivalent to c. So we will shift pattern P 6 times to align this occurrence with t in T.We are doing this because we already know that character c = “C” causes the mismatch. So any occurrence of t preceded by c will again cause mismatch when aligned with t, so that’s why it is better to skip this." }, { "code": null, "e": 28335, "s": 28295, "text": "Preprocessing for Good suffix heuristic" }, { "code": null, "e": 28672, "s": 28335, "text": "As a part of preprocessing, an array shift is created. Each entry shift[i] contain the distance pattern will shift if mismatch occur at position i-1. That is, the suffix of pattern starting at position i is matched and a mismatch occur at position i-1. Preprocessing is done separately for strong good suffix and case 2 discussed above." }, { "code": null, "e": 28990, "s": 28672, "text": "1) Preprocessing for Strong Good SuffixBefore discussing preprocessing, let us first discuss the idea of border. A border is a substring which is both proper suffix and proper prefix. For example, in string “ccacc”, “c” is a border, “cc” is a border because it appears in both end of string but “cca” is not a border." }, { "code": null, "e": 29411, "s": 28990, "text": "As a part of preprocessing an array bpos (border position) is calculated. Each entry bpos[i] contains the starting index of border for suffix starting at index i in given pattern P.The suffix φ beginning at position m has no border, so bpos[m] is set to m+1 where m is the length of the pattern.The shift position is obtained by the borders which cannot be extended to the left. Following is the code for preprocessing –" }, { "code": null, "e": 29769, "s": 29411, "text": "void preprocess_strong_suffix(int *shift, int *bpos,\n char *pat, int m)\n{\n int i = m, j = m+1;\n bpos[i] = j;\n while(i > 0)\n {\n while(j <= m && pat[i-1] != pat[j-1])\n {\n if (shift[j] == 0)\n shift[j] = j-i;\n j = bpos[j];\n }\n i--; j--;\n bpos[i] = j; \n }\n}\n" }, { "code": null, "e": 29821, "s": 29769, "text": "Explanation: Consider pattern P = “ABBABAB”, m = 7." }, { "code": null, "e": 29935, "s": 29821, "text": "The widest border of suffix “AB” beginning at position i = 5 is φ(nothing) starting at position 7 so bpos[5] = 7." }, { "code": null, "e": 45157, "s": 29935, "text": "At position i = 2 the suffix is “BABAB”. The widest border for this suffix is “BAB” starting at position 4, so j = bpos[2] = 4.We can understand bpos[i] = j using following example –If character # Which is at position i-1 is equivalent to character ? at position j-1, we know that border will be ? + border of suffix at position i which is starting at position j which is equivalent to saying that border of suffix at i-1 begin at j-1 or bpos[ i-1 ] = j-1 or in the code –i--; \nj--; \nbpos[ i ] = j\nBut if character # at position i-1 do not match with character ? at position j-1 then we continue our search to the right. Now we know that –Border width will be smaller than the border starting at position j ie. smaller than x...φBorder has to begin with # and end with φ or could be empty (no border exist).With above two facts we will continue our search in sub string x...φ from position j to m. The next border should be at j = bpos[j]. After updating j, we again compare character at position j-1 (?) with # and if they are equal then we got our border otherwise we continue our search to right until j>m. This process is shown by code –while(j <= m && pat[i-1] != pat[j-1])\n{\n j = bpos[j];\n}\ni--; j--;\nbpos[i]=j;\nIn above code look at these conditions –pat[i-1] != pat[j-1] \nThis is the condition which we discussed in case 2. When the character preceding the occurrence of t in pattern P is different than mismatching character in P, we stop skipping the occurrences and shift the pattern. So here P[i] == P[j] but P[i-1] != p[j-1] so we shift pattern from i to j. So shift[j] = j-i is recorder for j. So whenever any mismatch occur at position j we will shift the pattern shift[j+1] positions to the right.In above code the following condition is very important –if (shift[j] == 0 )\nThis condition prevent modification of shift[j] value from suffix having same border. For example, Consider pattern P = “addbddcdd”, when we calculate bpos[ i-1 ] for i = 4 then j = 7 in this case. we will be eventually setting value of shift[ 7 ] = 3. Now if we calculate bpos[ i-1 ] for i = 1 then j = 7 and we will be setting value shift[ 7 ] = 6 again if there is no test shift[ j ] == 0. This mean if we have a mismatch at position 6 we will shift pattern P 3 positions to right not 6 position.2) Preprocessing for Case 2In the preprocessing for case 2, for each suffix the widest border of the whole pattern that is contained in that suffix is determined.The starting position of the widest border of the pattern at all is stored in bpos[0]In the following preprocessing algorithm, this value bpos[0] is stored initially in all free entries of array shift. But when the suffix of the pattern becomes shorter than bpos[0], the algorithm continues with the next-wider border of the pattern, i.e. with bpos[j].Following is the implementation of the search algorithm –C++JavaPython3C#C++/* C program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string */ #include <stdio.h>#include <string.h> // preprocessing for strong good suffix rulevoid preprocess_strong_suffix(int *shift, int *bpos, char *pat, int m){ // m is the length of pattern int i=m, j=m+1; bpos[i]=j; while(i>0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j<=m && pat[i-1] != pat[j-1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j]==0) shift[j] = j-i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--;j--; bpos[i] = j; }} //Preprocessing for case 2void preprocess_case2(int *shift, int *bpos, char *pat, int m){ int i, j; j = bpos[0]; for(i=0; i<=m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i]==0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i==j) j = bpos[j]; }} /*Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule */void search(char *text, char *pat){ // s is shift of the pattern with respect to text int s=0, j; int m = strlen(pat); int n = strlen(text); int bpos[m+1], shift[m+1]; //initialize all occurrence of shift to 0 for(int i=0;i<m+1;i++) shift[i]=0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n-m) { j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j<0) { printf(\"pattern occurs at shift = %d\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j+1]; } } //Driver int main(){ char text[] = \"ABAAAABAACD\"; char pat[] = \"ABA\"; search(text, pat); return 0;}Java/* Java program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.length; int n = text.length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; //initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.printf(\"pattern occurs at shift = %d\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; } } // Driver Codepublic static void main(String[] args) { char []text = \"ABAAAABAACD\".toCharArray(); char []pat = \"ABA\".toCharArray(); search(text, pat);}} // This code is contributed by 29AjayKumarPython3# Python3 program for Boyer Moore Algorithm with # Good Suffix heuristic to find pattern in # given text string # preprocessing for strong good suffix ruledef preprocess_strong_suffix(shift, bpos, pat, m): # m is the length of pattern i = m j = m + 1 bpos[i] = j while i > 0: '''if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border ''' while j <= m and pat[i - 1] != pat[j - 1]: ''' the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j ''' if shift[j] == 0: shift[j] = j - i # Update the position of next border j = bpos[j] ''' p[i-1] matched with p[j-1], border is found. store the beginning position of border ''' i -= 1 j -= 1 bpos[i] = j # Preprocessing for case 2def preprocess_case2(shift, bpos, pat, m): j = bpos[0] for i in range(m + 1): ''' set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 ''' if shift[i] == 0: shift[i] = j ''' suffix becomes shorter than bpos[0], use the position of next widest border as value of j ''' if i == j: j = bpos[j] '''Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule '''def search(text, pat): # s is shift of the pattern with respect to text s = 0 m = len(pat) n = len(text) bpos = [0] * (m + 1) # initialize all occurrence of shift to 0 shift = [0] * (m + 1) # do preprocessing preprocess_strong_suffix(shift, bpos, pat, m) preprocess_case2(shift, bpos, pat, m) while s <= n - m: j = m - 1 ''' Keep reducing index j of pattern while characters of pattern and text are matching at this shift s''' while j >= 0 and pat[j] == text[s + j]: j -= 1 ''' If the pattern is present at the current shift, then index j will become -1 after the above loop ''' if j < 0: print(\"pattern occurs at shift = %d\" % s) s += shift[0] else: '''pat[i] != pat[s+j] so shift the pattern shift[j+1] times ''' s += shift[j + 1] # Driver Codeif __name__ == \"__main__\": text = \"ABAAAABAACD\" pat = \"ABA\" search(text, pat) # This code is contributed by# sanjeev2552C#/* C# program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */using System; class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.Length; int n = text.Length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; // initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; // do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s + j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.Write(\"pattern occurs at shift = {0}\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; }} // Driver Codepublic static void Main(String[] args) { char []text = \"ABAAAABAACD\".ToCharArray(); char []pat = \"ABA\".ToCharArray(); search(text, pat);}} // This code is contributed by PrinciRaj1992Output:pattern occurs at shift = 0\npattern occurs at shift = 5\nReferenceshttp://www.iti.fh-flensburg.de/lang/algorithmen/pattern/bmen.htmThis article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 45213, "s": 45157, "text": "We can understand bpos[i] = j using following example –" }, { "code": null, "e": 45504, "s": 45213, "text": "If character # Which is at position i-1 is equivalent to character ? at position j-1, we know that border will be ? + border of suffix at position i which is starting at position j which is equivalent to saying that border of suffix at i-1 begin at j-1 or bpos[ i-1 ] = j-1 or in the code –" }, { "code": null, "e": 45531, "s": 45504, "text": "i--; \nj--; \nbpos[ i ] = j\n" }, { "code": null, "e": 45673, "s": 45531, "text": "But if character # at position i-1 do not match with character ? at position j-1 then we continue our search to the right. Now we know that –" }, { "code": null, "e": 45842, "s": 45673, "text": "Border width will be smaller than the border starting at position j ie. smaller than x...φBorder has to begin with # and end with φ or could be empty (no border exist)." }, { "code": null, "e": 45933, "s": 45842, "text": "Border width will be smaller than the border starting at position j ie. smaller than x...φ" }, { "code": null, "e": 46012, "s": 45933, "text": "Border has to begin with # and end with φ or could be empty (no border exist)." }, { "code": null, "e": 46347, "s": 46012, "text": "With above two facts we will continue our search in sub string x...φ from position j to m. The next border should be at j = bpos[j]. After updating j, we again compare character at position j-1 (?) with # and if they are equal then we got our border otherwise we continue our search to right until j>m. This process is shown by code –" }, { "code": null, "e": 46428, "s": 46347, "text": "while(j <= m && pat[i-1] != pat[j-1])\n{\n j = bpos[j];\n}\ni--; j--;\nbpos[i]=j;\n" }, { "code": null, "e": 46469, "s": 46428, "text": "In above code look at these conditions –" }, { "code": null, "e": 46492, "s": 46469, "text": "pat[i-1] != pat[j-1] \n" }, { "code": null, "e": 46983, "s": 46492, "text": "This is the condition which we discussed in case 2. When the character preceding the occurrence of t in pattern P is different than mismatching character in P, we stop skipping the occurrences and shift the pattern. So here P[i] == P[j] but P[i-1] != p[j-1] so we shift pattern from i to j. So shift[j] = j-i is recorder for j. So whenever any mismatch occur at position j we will shift the pattern shift[j+1] positions to the right.In above code the following condition is very important –" }, { "code": null, "e": 47004, "s": 46983, "text": "if (shift[j] == 0 )\n" }, { "code": null, "e": 47504, "s": 47004, "text": "This condition prevent modification of shift[j] value from suffix having same border. For example, Consider pattern P = “addbddcdd”, when we calculate bpos[ i-1 ] for i = 4 then j = 7 in this case. we will be eventually setting value of shift[ 7 ] = 3. Now if we calculate bpos[ i-1 ] for i = 1 then j = 7 and we will be setting value shift[ 7 ] = 6 again if there is no test shift[ j ] == 0. This mean if we have a mismatch at position 6 we will shift pattern P 3 positions to right not 6 position." }, { "code": null, "e": 48019, "s": 47504, "text": "2) Preprocessing for Case 2In the preprocessing for case 2, for each suffix the widest border of the whole pattern that is contained in that suffix is determined.The starting position of the widest border of the pattern at all is stored in bpos[0]In the following preprocessing algorithm, this value bpos[0] is stored initially in all free entries of array shift. But when the suffix of the pattern becomes shorter than bpos[0], the algorithm continues with the next-wider border of the pattern, i.e. with bpos[j]." }, { "code": null, "e": 48077, "s": 48019, "text": "Following is the implementation of the search algorithm –" }, { "code": null, "e": 48081, "s": 48077, "text": "C++" }, { "code": null, "e": 48086, "s": 48081, "text": "Java" }, { "code": null, "e": 48094, "s": 48086, "text": "Python3" }, { "code": null, "e": 48097, "s": 48094, "text": "C#" }, { "code": "/* C program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string */ #include <stdio.h>#include <string.h> // preprocessing for strong good suffix rulevoid preprocess_strong_suffix(int *shift, int *bpos, char *pat, int m){ // m is the length of pattern int i=m, j=m+1; bpos[i]=j; while(i>0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j<=m && pat[i-1] != pat[j-1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j]==0) shift[j] = j-i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--;j--; bpos[i] = j; }} //Preprocessing for case 2void preprocess_case2(int *shift, int *bpos, char *pat, int m){ int i, j; j = bpos[0]; for(i=0; i<=m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i]==0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i==j) j = bpos[j]; }} /*Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule */void search(char *text, char *pat){ // s is shift of the pattern with respect to text int s=0, j; int m = strlen(pat); int n = strlen(text); int bpos[m+1], shift[m+1]; //initialize all occurrence of shift to 0 for(int i=0;i<m+1;i++) shift[i]=0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n-m) { j = m-1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j<0) { printf(\"pattern occurs at shift = %d\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j+1]; } } //Driver int main(){ char text[] = \"ABAAAABAACD\"; char pat[] = \"ABA\"; search(text, pat); return 0;}", "e": 50931, "s": 48097, "text": null }, { "code": "/* Java program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.length; int n = text.length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; //initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; //do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s+j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { System.out.printf(\"pattern occurs at shift = %d\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; } } // Driver Codepublic static void main(String[] args) { char []text = \"ABAAAABAACD\".toCharArray(); char []pat = \"ABA\".toCharArray(); search(text, pat);}} // This code is contributed by 29AjayKumar", "e": 53984, "s": 50931, "text": null }, { "code": "# Python3 program for Boyer Moore Algorithm with # Good Suffix heuristic to find pattern in # given text string # preprocessing for strong good suffix ruledef preprocess_strong_suffix(shift, bpos, pat, m): # m is the length of pattern i = m j = m + 1 bpos[i] = j while i > 0: '''if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border ''' while j <= m and pat[i - 1] != pat[j - 1]: ''' the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j ''' if shift[j] == 0: shift[j] = j - i # Update the position of next border j = bpos[j] ''' p[i-1] matched with p[j-1], border is found. store the beginning position of border ''' i -= 1 j -= 1 bpos[i] = j # Preprocessing for case 2def preprocess_case2(shift, bpos, pat, m): j = bpos[0] for i in range(m + 1): ''' set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 ''' if shift[i] == 0: shift[i] = j ''' suffix becomes shorter than bpos[0], use the position of next widest border as value of j ''' if i == j: j = bpos[j] '''Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule '''def search(text, pat): # s is shift of the pattern with respect to text s = 0 m = len(pat) n = len(text) bpos = [0] * (m + 1) # initialize all occurrence of shift to 0 shift = [0] * (m + 1) # do preprocessing preprocess_strong_suffix(shift, bpos, pat, m) preprocess_case2(shift, bpos, pat, m) while s <= n - m: j = m - 1 ''' Keep reducing index j of pattern while characters of pattern and text are matching at this shift s''' while j >= 0 and pat[j] == text[s + j]: j -= 1 ''' If the pattern is present at the current shift, then index j will become -1 after the above loop ''' if j < 0: print(\"pattern occurs at shift = %d\" % s) s += shift[0] else: '''pat[i] != pat[s+j] so shift the pattern shift[j+1] times ''' s += shift[j + 1] # Driver Codeif __name__ == \"__main__\": text = \"ABAAAABAACD\" pat = \"ABA\" search(text, pat) # This code is contributed by# sanjeev2552", "e": 56732, "s": 53984, "text": null }, { "code": "/* C# program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern ingiven text string */using System; class GFG { // preprocessing for strong good suffix rulestatic void preprocess_strong_suffix(int []shift, int []bpos, char []pat, int m){ // m is the length of pattern int i = m, j = m + 1; bpos[i] = j; while(i > 0) { /*if character at position i-1 is not equivalent to character at j-1, then continue searching to right of the pattern for border */ while(j <= m && pat[i - 1] != pat[j - 1]) { /* the character preceding the occurrence of t in pattern P is different than the mismatching character in P, we stop skipping the occurrences and shift the pattern from i to j */ if (shift[j] == 0) shift[j] = j - i; //Update the position of next border j = bpos[j]; } /* p[i-1] matched with p[j-1], border is found. store the beginning position of border */ i--; j--; bpos[i] = j; }} //Preprocessing for case 2static void preprocess_case2(int []shift, int []bpos, char []pat, int m){ int i, j; j = bpos[0]; for(i = 0; i <= m; i++) { /* set the border position of the first character of the pattern to all indices in array shift having shift[i] = 0 */ if(shift[i] == 0) shift[i] = j; /* suffix becomes shorter than bpos[0], use the position of next widest border as value of j */ if (i == j) j = bpos[j]; }} /*Search for a pattern in given text usingBoyer Moore algorithm with Good suffix rule */static void search(char []text, char []pat){ // s is shift of the pattern // with respect to text int s = 0, j; int m = pat.Length; int n = text.Length; int []bpos = new int[m + 1]; int []shift = new int[m + 1]; // initialize all occurrence of shift to 0 for(int i = 0; i < m + 1; i++) shift[i] = 0; // do preprocessing preprocess_strong_suffix(shift, bpos, pat, m); preprocess_case2(shift, bpos, pat, m); while(s <= n - m) { j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s*/ while(j >= 0 && pat[j] == text[s + j]) j--; /* If the pattern is present at the current shift, then index j will become -1 after the above loop */ if (j < 0) { Console.Write(\"pattern occurs at shift = {0}\\n\", s); s += shift[0]; } else /*pat[i] != pat[s+j] so shift the pattern shift[j+1] times */ s += shift[j + 1]; }} // Driver Codepublic static void Main(String[] args) { char []text = \"ABAAAABAACD\".ToCharArray(); char []pat = \"ABA\".ToCharArray(); search(text, pat);}} // This code is contributed by PrinciRaj1992", "e": 59834, "s": 56732, "text": null }, { "code": null, "e": 59891, "s": 59834, "text": "pattern occurs at shift = 0\npattern occurs at shift = 5\n" }, { "code": null, "e": 59902, "s": 59891, "text": "References" }, { "code": null, "e": 59967, "s": 59902, "text": "http://www.iti.fh-flensburg.de/lang/algorithmen/pattern/bmen.htm" }, { "code": null, "e": 60265, "s": 59967, "text": "This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 60390, "s": 60265, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 60403, "s": 60390, "text": "Kirti_Mangal" }, { "code": null, "e": 60414, "s": 60403, "text": "nidhi_biet" }, { "code": null, "e": 60426, "s": 60414, "text": "29AjayKumar" }, { "code": null, "e": 60440, "s": 60426, "text": "princiraj1992" }, { "code": null, "e": 60452, "s": 60440, "text": "sanjeev2552" }, { "code": null, "e": 60470, "s": 60452, "text": "Pattern Searching" }, { "code": null, "e": 60488, "s": 60470, "text": "Pattern Searching" }, { "code": null, "e": 60586, "s": 60488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 60660, "s": 60586, "text": "Count N-length strings consisting only of vowels sorted lexicographically" }, { "code": null, "e": 60747, "s": 60660, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 60783, "s": 60747, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 60826, "s": 60783, "text": "Applications of String Matching Algorithms" }, { "code": null, "e": 60879, "s": 60826, "text": "Remove leading zeros from a Number given as a string" }, { "code": null, "e": 60934, "s": 60879, "text": "How to validate a domain name using Regular Expression" }, { "code": null, "e": 60970, "s": 60934, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 61041, "s": 60970, "text": "Split the binary string into substrings with equal number of 0s and 1s" }, { "code": null, "e": 61095, "s": 61041, "text": "Check if a string consists only of special characters" } ]
Prototype - toObject() Method
This method returns a cloned, vanilla object. hash.toObject(); Returns a cloned, vanilla object. <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function showResult() { var h = new Hash({ a: 'apple', b: 'banana', c: 'coconut' }); var obj = h.toObject(); alert( "Object.inspect(h) : " + Object.inspect(h) ); alert( "Object.inspect(obj) : " + Object.inspect(obj) ); alert( "h.get('a') : " + h.get('a') ); alert( "Object.keys(obj) : " + Object.keys(obj) ); } </script> </head> <body> <p>Click the button to see the result.</p> <br /> <br /> <input type = "button" value = "Result" onclick = "showResult();"/> </body> </html> Click the button to see the result. 127 Lectures 11.5 hours Aleksandar Cucukovic Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 2061, "text": "This method returns a cloned, vanilla object." }, { "code": null, "e": 2125, "s": 2107, "text": "hash.toObject();\n" }, { "code": null, "e": 2159, "s": 2125, "text": "Returns a cloned, vanilla object." }, { "code": null, "e": 2927, "s": 2159, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function showResult() {\n var h = new Hash({ a: 'apple', b: 'banana', c: 'coconut' });\n var obj = h.toObject();\n alert( \"Object.inspect(h) : \" + Object.inspect(h) );\n alert( \"Object.inspect(obj) : \" + Object.inspect(obj) );\n alert( \"h.get('a') : \" + h.get('a') );\n alert( \"Object.keys(obj) : \" + Object.keys(obj) );\n }\n </script>\n </head>\n\n <body>\n <p>Click the button to see the result.</p>\n <br />\n <br />\n <input type = \"button\" value = \"Result\" onclick = \"showResult();\"/>\n </body>\n</html>" }, { "code": null, "e": 2963, "s": 2927, "text": "Click the button to see the result." }, { "code": null, "e": 3000, "s": 2963, "text": "\n 127 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3022, "s": 3000, "text": " Aleksandar Cucukovic" }, { "code": null, "e": 3029, "s": 3022, "text": " Print" }, { "code": null, "e": 3040, "s": 3029, "text": " Add Notes" } ]
Multi-Class Text Classification Model Comparison and Selection | by Susan Li | Towards Data Science
When working on a supervised machine learning problem with a given data set, we try different algorithms and techniques to search for models to produce general hypotheses, which then make the most accurate predictions possible about future instances. The same principles apply to text (or document) classification where there are many models can be used to train a text classifier. The answer to the question “What machine learning model should I use?” is always “It depends.” Even the most experienced data scientists can’t tell which algorithm will perform best before experimenting them. This is what we are going to do today: use everything that we have presented about text classification in the previous articles (and more) and comparing between the text classification models we trained in order to choose the most accurate one for our problem. We are using a relatively large data set of Stack Overflow questions and tags. The data is available in Google BigQuery, it is also publicly available at this Cloud Storage URL: https://storage.googleapis.com/tensorflow-workshop-examples/stack-overflow-data.csv. 10276752 We have over 10 million words in the data. my_tags = ['java','html','asp.net','c#','ruby-on-rails','jquery','mysql','php','ios','javascript','python','c','css','android','iphone','sql','objective-c','c++','angularjs','.net']plt.figure(figsize=(10,4))df.tags.value_counts().plot(kind='bar'); The classes are very well balanced. We want to have a look a few post and tag pairs. def print_plot(index): example = df[df.index == index][['post', 'tags']].values[0] if len(example) > 0: print(example[0]) print('Tag:', example[1])print_plot(10) print_plot(30) As you can see, the texts need to be cleaned up. The text cleaning techniques we have seen so far work very well in practice. Depending on the kind of texts you may encounter, it may be relevant to include more complex text cleaning steps. But keep in mind that the more steps we add, the longer the text cleaning will take. For this particular data set, our text cleaning step includes HTML decoding, remove stop words, change text to lower case, remove punctuation, remove bad characters, and so on. Now we can have a look a cleaned post: Way better! df['post'].apply(lambda x: len(x.split(' '))).sum() 3421180 After text cleaning and removing stop words, we have only over 3 million words to work with! After splitting the data set, the next steps includes feature engineering. We will convert our text documents to a matrix of token counts (CountVectorizer), then transform a count matrix to a normalized tf-idf representation (tf-idf transformer). After that, we train several classifiers from Scikit-Learn library. X = df.posty = df.tagsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 42) After we have our features, we can train a classifier to try to predict the tag of a post. We will start with a Naive Bayes classifier, which provides a nice baseline for this task. scikit-learn includes several variants of this classifier; the one most suitable for text is the multinomial variant. To make the vectorizer => transformer => classifier easier to work with, we will use Pipeline class in Scilkit-Learn that behaves like a compound classifier. We achieved 74% accuracy. Linear Support Vector Machine is widely regarded as one of the best text classification algorithms. We achieve a higher accuracy score of 79% which is 5% improvement over Naive Bayes. Logistic regression is a simple and easy to understand classification algorithm, and Logistic regression can be easily generalized to multiple classes. We achieve an accuracy score of 78% which is 4% higher than Naive Bayes and 1% lower than SVM. As you can see, following some very basic steps and using a simple linear model, we were able to reach as high as an 79% accuracy on this multi-class text classification data set. Using the same data set, we are going to try some advanced techniques such as word embedding and neural networks. Now, let’s try some complex features than just simply counting words. Word2vec, like doc2vec, belongs to the text preprocessing phase. Specifically, to the part that transforms a text into a row of numbers. Word2vec is a type of mapping that allows words with similar meaning to have similar vector representation. The idea behind Word2vec is rather simple: we want to use the surrounding words to represent the target words with a Neural Network whose hidden layer encodes the word representation. First we load a word2vec model. It has been pre-trained by Google on a 100 billion word Google News corpus. from gensim.models import Word2Vecwv = gensim.models.KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin.gz", binary=True)wv.init_sims(replace=True) We may want to explore some vocabularies. from itertools import islicelist(islice(wv.vocab, 13030, 13050)) BOW based approaches that includes averaging, summation, weighted addition. The common way is to average the two word vectors. Therefore, we will follow the most common way. We will tokenize the text and apply the tokenization to “post” column, and apply word vector averaging to tokenized text. Its time to see how logistic regression classifiers performs on these word-averaging document features. from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression(n_jobs=1, C=1e5)logreg = logreg.fit(X_train_word_average, train['tags'])y_pred = logreg.predict(X_test_word_average)print('accuracy %s' % accuracy_score(y_pred, test.tags))print(classification_report(test.tags, y_pred,target_names=my_tags)) It was disappointing, worst we have seen so far. The same idea of word2vec can be extended to documents where instead of learning feature representations for words, we learn it for sentences or documents. To get a general idea of a word2vec, think of it as a mathematical average of the word vector representations of all the words in the document. Doc2Vec extends the idea of word2vec, however words can only capture so much, there are times when we need relationships between documents and not just words. The way to train doc2vec model for our Stack Overflow questions and tags data is very similar with when we train Multi-Class Text Classification with Doc2vec and Logistic Regression. First, we label the sentences. Gensim’s Doc2Vec implementation requires each document/paragraph to have a label associated with it. and we do this by using the TaggedDocument method. The format will be “TRAIN_i” or “TEST_i” where “i” is a dummy index of the post. According to Gensim doc2vec tutorial, its doc2vec class was trained on the entire data, and we will do the same. Let’s have a look what the tagged document looks like: all_data[:2] When training the doc2vec, we will vary the following parameters: dm=0 , distributed bag of words (DBOW) is used. vector_size=300 , 300 vector dimensional feature vectors. negative=5 , specifies how many “noise words” should be drawn. min_count=1, ignores all words with total frequency lower than this. alpha=0.065 , the initial learning rate. We initialize the model and train for 30 epochs. Next, we get vectors from trained doc2vec model. Finally, we get a logistic regression model trained by the doc2vec features. logreg = LogisticRegression(n_jobs=1, C=1e5)logreg.fit(train_vectors_dbow, y_train)logreg = logreg.fit(train_vectors_dbow, y_train)y_pred = logreg.predict(test_vectors_dbow)print('accuracy %s' % accuracy_score(y_pred, y_test))print(classification_report(y_test, y_pred,target_names=my_tags)) We achieve an accuracy score of 80% which is 1% higher than SVM. Finally, we are going to do a text classification with Keras which is a Python Deep Learning library. The following code were largely taken from a Google workshop. The process is like this: Separate the data into training and test sets. Use tokenizer methods to count the unique words in our vocabulary and assign each of those words to indices. Calling fit_on_texts() automatically creates a word index lookup of our vocabulary. We limit our vocabulary to the top words by passing a num_words param to the tokenizer. With our tokenizer, we can now use the texts_to_matrix method to create the training data that we’ll pass our model. We feed a one-hot vector to our model. After we transform our features and labels in a format Keras can read, we are ready to build our text classification model. When we build our model, all we need to do is tell Keras the shape of our input data, output data, and the type of each layer. keras will look after the rest. When training the model, we’ll call the fit() method, pass it our training data and labels, batch size and epochs. The accuracy is: score = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=1)print('Test accuracy:', score[1]) So, which model is the best for this particular data set? I will leave it to you to decide. Jupyter notebook can be found on Github. Have a productive day!
[ { "code": null, "e": 638, "s": 47, "text": "When working on a supervised machine learning problem with a given data set, we try different algorithms and techniques to search for models to produce general hypotheses, which then make the most accurate predictions possible about future instances. The same principles apply to text (or document) classification where there are many models can be used to train a text classifier. The answer to the question “What machine learning model should I use?” is always “It depends.” Even the most experienced data scientists can’t tell which algorithm will perform best before experimenting them." }, { "code": null, "e": 899, "s": 638, "text": "This is what we are going to do today: use everything that we have presented about text classification in the previous articles (and more) and comparing between the text classification models we trained in order to choose the most accurate one for our problem." }, { "code": null, "e": 1162, "s": 899, "text": "We are using a relatively large data set of Stack Overflow questions and tags. The data is available in Google BigQuery, it is also publicly available at this Cloud Storage URL: https://storage.googleapis.com/tensorflow-workshop-examples/stack-overflow-data.csv." }, { "code": null, "e": 1171, "s": 1162, "text": "10276752" }, { "code": null, "e": 1214, "s": 1171, "text": "We have over 10 million words in the data." }, { "code": null, "e": 1462, "s": 1214, "text": "my_tags = ['java','html','asp.net','c#','ruby-on-rails','jquery','mysql','php','ios','javascript','python','c','css','android','iphone','sql','objective-c','c++','angularjs','.net']plt.figure(figsize=(10,4))df.tags.value_counts().plot(kind='bar');" }, { "code": null, "e": 1498, "s": 1462, "text": "The classes are very well balanced." }, { "code": null, "e": 1547, "s": 1498, "text": "We want to have a look a few post and tag pairs." }, { "code": null, "e": 1729, "s": 1547, "text": "def print_plot(index): example = df[df.index == index][['post', 'tags']].values[0] if len(example) > 0: print(example[0]) print('Tag:', example[1])print_plot(10)" }, { "code": null, "e": 1744, "s": 1729, "text": "print_plot(30)" }, { "code": null, "e": 1793, "s": 1744, "text": "As you can see, the texts need to be cleaned up." }, { "code": null, "e": 2069, "s": 1793, "text": "The text cleaning techniques we have seen so far work very well in practice. Depending on the kind of texts you may encounter, it may be relevant to include more complex text cleaning steps. But keep in mind that the more steps we add, the longer the text cleaning will take." }, { "code": null, "e": 2246, "s": 2069, "text": "For this particular data set, our text cleaning step includes HTML decoding, remove stop words, change text to lower case, remove punctuation, remove bad characters, and so on." }, { "code": null, "e": 2285, "s": 2246, "text": "Now we can have a look a cleaned post:" }, { "code": null, "e": 2297, "s": 2285, "text": "Way better!" }, { "code": null, "e": 2349, "s": 2297, "text": "df['post'].apply(lambda x: len(x.split(' '))).sum()" }, { "code": null, "e": 2357, "s": 2349, "text": "3421180" }, { "code": null, "e": 2450, "s": 2357, "text": "After text cleaning and removing stop words, we have only over 3 million words to work with!" }, { "code": null, "e": 2765, "s": 2450, "text": "After splitting the data set, the next steps includes feature engineering. We will convert our text documents to a matrix of token counts (CountVectorizer), then transform a count matrix to a normalized tf-idf representation (tf-idf transformer). After that, we train several classifiers from Scikit-Learn library." }, { "code": null, "e": 2879, "s": 2765, "text": "X = df.posty = df.tagsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 42)" }, { "code": null, "e": 3179, "s": 2879, "text": "After we have our features, we can train a classifier to try to predict the tag of a post. We will start with a Naive Bayes classifier, which provides a nice baseline for this task. scikit-learn includes several variants of this classifier; the one most suitable for text is the multinomial variant." }, { "code": null, "e": 3337, "s": 3179, "text": "To make the vectorizer => transformer => classifier easier to work with, we will use Pipeline class in Scilkit-Learn that behaves like a compound classifier." }, { "code": null, "e": 3363, "s": 3337, "text": "We achieved 74% accuracy." }, { "code": null, "e": 3463, "s": 3363, "text": "Linear Support Vector Machine is widely regarded as one of the best text classification algorithms." }, { "code": null, "e": 3547, "s": 3463, "text": "We achieve a higher accuracy score of 79% which is 5% improvement over Naive Bayes." }, { "code": null, "e": 3699, "s": 3547, "text": "Logistic regression is a simple and easy to understand classification algorithm, and Logistic regression can be easily generalized to multiple classes." }, { "code": null, "e": 3794, "s": 3699, "text": "We achieve an accuracy score of 78% which is 4% higher than Naive Bayes and 1% lower than SVM." }, { "code": null, "e": 3974, "s": 3794, "text": "As you can see, following some very basic steps and using a simple linear model, we were able to reach as high as an 79% accuracy on this multi-class text classification data set." }, { "code": null, "e": 4088, "s": 3974, "text": "Using the same data set, we are going to try some advanced techniques such as word embedding and neural networks." }, { "code": null, "e": 4158, "s": 4088, "text": "Now, let’s try some complex features than just simply counting words." }, { "code": null, "e": 4403, "s": 4158, "text": "Word2vec, like doc2vec, belongs to the text preprocessing phase. Specifically, to the part that transforms a text into a row of numbers. Word2vec is a type of mapping that allows words with similar meaning to have similar vector representation." }, { "code": null, "e": 4587, "s": 4403, "text": "The idea behind Word2vec is rather simple: we want to use the surrounding words to represent the target words with a Neural Network whose hidden layer encodes the word representation." }, { "code": null, "e": 4695, "s": 4587, "text": "First we load a word2vec model. It has been pre-trained by Google on a 100 billion word Google News corpus." }, { "code": null, "e": 4862, "s": 4695, "text": "from gensim.models import Word2Vecwv = gensim.models.KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin.gz\", binary=True)wv.init_sims(replace=True)" }, { "code": null, "e": 4904, "s": 4862, "text": "We may want to explore some vocabularies." }, { "code": null, "e": 4969, "s": 4904, "text": "from itertools import islicelist(islice(wv.vocab, 13030, 13050))" }, { "code": null, "e": 5143, "s": 4969, "text": "BOW based approaches that includes averaging, summation, weighted addition. The common way is to average the two word vectors. Therefore, we will follow the most common way." }, { "code": null, "e": 5265, "s": 5143, "text": "We will tokenize the text and apply the tokenization to “post” column, and apply word vector averaging to tokenized text." }, { "code": null, "e": 5369, "s": 5265, "text": "Its time to see how logistic regression classifiers performs on these word-averaging document features." }, { "code": null, "e": 5689, "s": 5369, "text": "from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression(n_jobs=1, C=1e5)logreg = logreg.fit(X_train_word_average, train['tags'])y_pred = logreg.predict(X_test_word_average)print('accuracy %s' % accuracy_score(y_pred, test.tags))print(classification_report(test.tags, y_pred,target_names=my_tags))" }, { "code": null, "e": 5738, "s": 5689, "text": "It was disappointing, worst we have seen so far." }, { "code": null, "e": 6197, "s": 5738, "text": "The same idea of word2vec can be extended to documents where instead of learning feature representations for words, we learn it for sentences or documents. To get a general idea of a word2vec, think of it as a mathematical average of the word vector representations of all the words in the document. Doc2Vec extends the idea of word2vec, however words can only capture so much, there are times when we need relationships between documents and not just words." }, { "code": null, "e": 6380, "s": 6197, "text": "The way to train doc2vec model for our Stack Overflow questions and tags data is very similar with when we train Multi-Class Text Classification with Doc2vec and Logistic Regression." }, { "code": null, "e": 6644, "s": 6380, "text": "First, we label the sentences. Gensim’s Doc2Vec implementation requires each document/paragraph to have a label associated with it. and we do this by using the TaggedDocument method. The format will be “TRAIN_i” or “TEST_i” where “i” is a dummy index of the post." }, { "code": null, "e": 6812, "s": 6644, "text": "According to Gensim doc2vec tutorial, its doc2vec class was trained on the entire data, and we will do the same. Let’s have a look what the tagged document looks like:" }, { "code": null, "e": 6825, "s": 6812, "text": "all_data[:2]" }, { "code": null, "e": 6891, "s": 6825, "text": "When training the doc2vec, we will vary the following parameters:" }, { "code": null, "e": 6939, "s": 6891, "text": "dm=0 , distributed bag of words (DBOW) is used." }, { "code": null, "e": 6997, "s": 6939, "text": "vector_size=300 , 300 vector dimensional feature vectors." }, { "code": null, "e": 7060, "s": 6997, "text": "negative=5 , specifies how many “noise words” should be drawn." }, { "code": null, "e": 7129, "s": 7060, "text": "min_count=1, ignores all words with total frequency lower than this." }, { "code": null, "e": 7170, "s": 7129, "text": "alpha=0.065 , the initial learning rate." }, { "code": null, "e": 7219, "s": 7170, "text": "We initialize the model and train for 30 epochs." }, { "code": null, "e": 7268, "s": 7219, "text": "Next, we get vectors from trained doc2vec model." }, { "code": null, "e": 7345, "s": 7268, "text": "Finally, we get a logistic regression model trained by the doc2vec features." }, { "code": null, "e": 7637, "s": 7345, "text": "logreg = LogisticRegression(n_jobs=1, C=1e5)logreg.fit(train_vectors_dbow, y_train)logreg = logreg.fit(train_vectors_dbow, y_train)y_pred = logreg.predict(test_vectors_dbow)print('accuracy %s' % accuracy_score(y_pred, y_test))print(classification_report(y_test, y_pred,target_names=my_tags))" }, { "code": null, "e": 7702, "s": 7637, "text": "We achieve an accuracy score of 80% which is 1% higher than SVM." }, { "code": null, "e": 7804, "s": 7702, "text": "Finally, we are going to do a text classification with Keras which is a Python Deep Learning library." }, { "code": null, "e": 7892, "s": 7804, "text": "The following code were largely taken from a Google workshop. The process is like this:" }, { "code": null, "e": 7939, "s": 7892, "text": "Separate the data into training and test sets." }, { "code": null, "e": 8048, "s": 7939, "text": "Use tokenizer methods to count the unique words in our vocabulary and assign each of those words to indices." }, { "code": null, "e": 8132, "s": 8048, "text": "Calling fit_on_texts() automatically creates a word index lookup of our vocabulary." }, { "code": null, "e": 8220, "s": 8132, "text": "We limit our vocabulary to the top words by passing a num_words param to the tokenizer." }, { "code": null, "e": 8337, "s": 8220, "text": "With our tokenizer, we can now use the texts_to_matrix method to create the training data that we’ll pass our model." }, { "code": null, "e": 8376, "s": 8337, "text": "We feed a one-hot vector to our model." }, { "code": null, "e": 8500, "s": 8376, "text": "After we transform our features and labels in a format Keras can read, we are ready to build our text classification model." }, { "code": null, "e": 8659, "s": 8500, "text": "When we build our model, all we need to do is tell Keras the shape of our input data, output data, and the type of each layer. keras will look after the rest." }, { "code": null, "e": 8774, "s": 8659, "text": "When training the model, we’ll call the fit() method, pass it our training data and labels, batch size and epochs." }, { "code": null, "e": 8791, "s": 8774, "text": "The accuracy is:" }, { "code": null, "e": 8919, "s": 8791, "text": "score = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=1)print('Test accuracy:', score[1])" }, { "code": null, "e": 9011, "s": 8919, "text": "So, which model is the best for this particular data set? I will leave it to you to decide." } ]
How to get items with a specific value from documents using MongoDB shell?
To get items with a specific value, simply use find(). Let us create a collection with documents − > db.demo563.insertOne({"Name":"Chris","Age":21,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f546c54b4472ed3e8e878") } > db.demo563.insertOne({"Name":"Bob","Age":23,"isMarried":false}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f547854b4472ed3e8e879") } > db.demo563.insertOne({"Name":"Carol","Age":23,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f548b54b4472ed3e8e87a") } > db.demo563.insertOne({"Name":"Mike","Age":21,"isMarried":true}){ "acknowledged" : true, "insertedId" : ObjectId("5e8f549454b4472ed3e8e87b") } Display all documents from a collection with the help of find() method − > db.demo563.find(); This will produce the following output − { "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true } { "_id" : ObjectId("5e8f547854b4472ed3e8e879"), "Name" : "Bob", "Age" : 23, "isMarried" : false } { "_id" : ObjectId("5e8f548b54b4472ed3e8e87a"), "Name" : "Carol", "Age" : 23, "isMarried" : true } { "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true } Following is the query to get items from documents using MongoDB shell > db.demo563.find({Age:21},{isMarried:true,Name:1,Age:1}); This will produce the following output − { "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true } { "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }
[ { "code": null, "e": 1161, "s": 1062, "text": "To get items with a specific value, simply use find(). Let us create a collection with documents −" }, { "code": null, "e": 1751, "s": 1161, "text": "> db.demo563.insertOne({\"Name\":\"Chris\",\"Age\":21,\"isMarried\":true}){\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f546c54b4472ed3e8e878\")\n}\n> db.demo563.insertOne({\"Name\":\"Bob\",\"Age\":23,\"isMarried\":false}){\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f547854b4472ed3e8e879\")\n}\n> db.demo563.insertOne({\"Name\":\"Carol\",\"Age\":23,\"isMarried\":true}){\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f548b54b4472ed3e8e87a\")\n}\n> db.demo563.insertOne({\"Name\":\"Mike\",\"Age\":21,\"isMarried\":true}){\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e8f549454b4472ed3e8e87b\")\n}" }, { "code": null, "e": 1824, "s": 1751, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1845, "s": 1824, "text": "> db.demo563.find();" }, { "code": null, "e": 1886, "s": 1845, "text": "This will produce the following output −" }, { "code": null, "e": 2280, "s": 1886, "text": "{ \"_id\" : ObjectId(\"5e8f546c54b4472ed3e8e878\"), \"Name\" : \"Chris\", \"Age\" : 21, \"isMarried\" : true }\n{ \"_id\" : ObjectId(\"5e8f547854b4472ed3e8e879\"), \"Name\" : \"Bob\", \"Age\" : 23, \"isMarried\" : false }\n{ \"_id\" : ObjectId(\"5e8f548b54b4472ed3e8e87a\"), \"Name\" : \"Carol\", \"Age\" : 23, \"isMarried\" : true }\n{ \"_id\" : ObjectId(\"5e8f549454b4472ed3e8e87b\"), \"Name\" : \"Mike\", \"Age\" : 21, \"isMarried\" : true }" }, { "code": null, "e": 2351, "s": 2280, "text": "Following is the query to get items from documents using MongoDB shell" }, { "code": null, "e": 2410, "s": 2351, "text": "> db.demo563.find({Age:21},{isMarried:true,Name:1,Age:1});" }, { "code": null, "e": 2451, "s": 2410, "text": "This will produce the following output −" }, { "code": null, "e": 2648, "s": 2451, "text": "{ \"_id\" : ObjectId(\"5e8f546c54b4472ed3e8e878\"), \"Name\" : \"Chris\", \"Age\" : 21, \"isMarried\" : true }\n{ \"_id\" : ObjectId(\"5e8f549454b4472ed3e8e87b\"), \"Name\" : \"Mike\", \"Age\" : 21, \"isMarried\" : true }" } ]
C library macro - setjmp()
The C library macro int setjmp(jmp_buf environment), saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then it returns the value passed to longjmp as a second argument. Following is the declaration for setjmp() macro. int setjmp(jmp_buf environment) environment − This is the object of type jmp_buf where the environment information is stored. environment − This is the object of type jmp_buf where the environment information is stored. This macro may return more than once. First time, on its direct invocation, it always returns zero. When longjmp is called with the information set to the environment, the macro returns again; now it returns the value passed to longjmp as second argument. The following example shows the usage of setjmp() macro. #include <stdio.h> #include <stdlib.h> #include <setjmp.h> int main () { int val; jmp_buf env_buffer; /* save calling environment for longjmp */ val = setjmp( env_buffer ); if( val != 0 ) { printf("Returned from a longjmp() with value = %s\n", val); exit(0); } printf("Jump function call\n"); jmpfunction( env_buffer ); return(0); } void jmpfunction(jmp_buf env_buf) { longjmp(env_buf, "tutorialspoint.com"); } Let us compile and run the above program, this will produce the following result − Jump function call Returned from a longjmp() with value = tutorialspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2351, "s": 2007, "text": "The C library macro int setjmp(jmp_buf environment), saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then it returns the value passed to longjmp as a second argument." }, { "code": null, "e": 2400, "s": 2351, "text": "Following is the declaration for setjmp() macro." }, { "code": null, "e": 2432, "s": 2400, "text": "int setjmp(jmp_buf environment)" }, { "code": null, "e": 2526, "s": 2432, "text": "environment − This is the object of type jmp_buf where the environment information is stored." }, { "code": null, "e": 2620, "s": 2526, "text": "environment − This is the object of type jmp_buf where the environment information is stored." }, { "code": null, "e": 2876, "s": 2620, "text": "This macro may return more than once. First time, on its direct invocation, it always returns zero. When longjmp is called with the information set to the environment, the macro returns again; now it returns the value passed to longjmp as second argument." }, { "code": null, "e": 2933, "s": 2876, "text": "The following example shows the usage of setjmp() macro." }, { "code": null, "e": 3401, "s": 2933, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <setjmp.h>\n\nint main () {\n int val;\n jmp_buf env_buffer;\n\n /* save calling environment for longjmp */\n val = setjmp( env_buffer );\n \n if( val != 0 ) {\n printf(\"Returned from a longjmp() with value = %s\\n\", val);\n exit(0);\n }\n \n printf(\"Jump function call\\n\");\n jmpfunction( env_buffer );\n \n return(0);\n}\n\nvoid jmpfunction(jmp_buf env_buf) {\n longjmp(env_buf, \"tutorialspoint.com\");\n}" }, { "code": null, "e": 3484, "s": 3401, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3562, "s": 3484, "text": "Jump function call\nReturned from a longjmp() with value = tutorialspoint.com\n" }, { "code": null, "e": 3595, "s": 3562, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3610, "s": 3595, "text": " Nishant Malik" }, { "code": null, "e": 3645, "s": 3610, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3660, "s": 3645, "text": " Nishant Malik" }, { "code": null, "e": 3695, "s": 3660, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3709, "s": 3695, "text": " Asif Hussain" }, { "code": null, "e": 3742, "s": 3709, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3760, "s": 3742, "text": " Richa Maheshwari" }, { "code": null, "e": 3795, "s": 3760, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3814, "s": 3795, "text": " Vandana Annavaram" }, { "code": null, "e": 3847, "s": 3814, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3859, "s": 3847, "text": " Amit Diwan" }, { "code": null, "e": 3866, "s": 3859, "text": " Print" }, { "code": null, "e": 3877, "s": 3866, "text": " Add Notes" } ]
SAS - One Way Anova
ANOVA stands for Analysis of Variance. In SAS it is done using PROC ANOVA. It performs analysis of data from a wide variety of experimental designs. In this process, a continuous response variable, known as a dependent variable, is measured under experimental conditions identified by classification variables, known as independent variables. The variation in the response is assumed to be due to effects in the classification, with random error accounting for the remaining variation. The basic syntax for applying PROC ANOVA in SAS is − PROC ANOVA dataset ; CLASS Variable; MODEL Variable1 = variable2 ; MEANS ; Following is the description of the parameters used − dataset is the name of the dataset. dataset is the name of the dataset. CLASS gives the variables the variable used as classification variable. CLASS gives the variables the variable used as classification variable. MODEL defines the model to be fit using certain variables from the dataset. MODEL defines the model to be fit using certain variables from the dataset. Variable_1 and Variable_2 are the variable names of the dataset used in analysis. Variable_1 and Variable_2 are the variable names of the dataset used in analysis. MEANS defines the type of computation and comparison of means. MEANS defines the type of computation and comparison of means. Let us now understand the concept of applying ANOVA in SAS. Lets consider the dataset SASHELP.CARS. Here we study the dependence between the variables car type and their horsepower. As the car type is a variable with categorical values, we take it as class variable and use both these variables in the MODEL. PROC ANOVA DATA = SASHELPS.CARS; CLASS type; MODEL horsepower = type; RUN; When the above code is executed, we get the following result − Let us now understand the concept of applying ANOVA with MEANS in SAS. We can also extend the model by applying the MEANS statement in which we use Turkey's Studentized method to compare the mean values of various car types.The category of car types are listed with the mean value of horsepower in each category along with some additional values like error mean square etc. PROC ANOVA DATA = SASHELPS.CARS; CLASS type; MODEL horsepower = type; MEANS type / tukey lines; RUN; When the above code is executed, we get the following result − 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 3069, "s": 2583, "text": "ANOVA stands for Analysis of Variance. In SAS it is done using PROC ANOVA. It performs analysis of data from a wide variety of experimental designs. In this process, a continuous response variable, known as a dependent variable, is measured under experimental conditions identified by classification variables, known as independent variables. The variation in the response is assumed to be due to effects in the classification, with random error accounting for the remaining variation." }, { "code": null, "e": 3122, "s": 3069, "text": "The basic syntax for applying PROC ANOVA in SAS is −" }, { "code": null, "e": 3197, "s": 3122, "text": "PROC ANOVA dataset ;\nCLASS Variable;\nMODEL Variable1 = variable2 ;\nMEANS ;" }, { "code": null, "e": 3251, "s": 3197, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3287, "s": 3251, "text": "dataset is the name of the dataset." }, { "code": null, "e": 3323, "s": 3287, "text": "dataset is the name of the dataset." }, { "code": null, "e": 3395, "s": 3323, "text": "CLASS gives the variables the variable used as classification variable." }, { "code": null, "e": 3467, "s": 3395, "text": "CLASS gives the variables the variable used as classification variable." }, { "code": null, "e": 3543, "s": 3467, "text": "MODEL defines the model to be fit using certain variables from the dataset." }, { "code": null, "e": 3619, "s": 3543, "text": "MODEL defines the model to be fit using certain variables from the dataset." }, { "code": null, "e": 3701, "s": 3619, "text": "Variable_1 and Variable_2 are the variable names of the dataset used in analysis." }, { "code": null, "e": 3783, "s": 3701, "text": "Variable_1 and Variable_2 are the variable names of the dataset used in analysis." }, { "code": null, "e": 3846, "s": 3783, "text": "MEANS defines the type of computation and comparison of means." }, { "code": null, "e": 3909, "s": 3846, "text": "MEANS defines the type of computation and comparison of means." }, { "code": null, "e": 3969, "s": 3909, "text": "Let us now understand the concept of applying ANOVA in SAS." }, { "code": null, "e": 4218, "s": 3969, "text": "Lets consider the dataset SASHELP.CARS. Here we study the dependence between the variables car type and their horsepower. As the car type is a variable with categorical values, we take it as class variable and use both these variables in the MODEL." }, { "code": null, "e": 4293, "s": 4218, "text": "PROC ANOVA DATA = SASHELPS.CARS;\nCLASS type;\nMODEL horsepower = type;\nRUN;" }, { "code": null, "e": 4356, "s": 4293, "text": "When the above code is executed, we get the following result −" }, { "code": null, "e": 4427, "s": 4356, "text": "Let us now understand the concept of applying ANOVA with MEANS in SAS." }, { "code": null, "e": 4730, "s": 4427, "text": "We can also extend the model by applying the MEANS statement in which we use Turkey's Studentized method to compare the mean values of various car types.The category of car types are listed with the mean value of horsepower in each category along with some additional values like error mean square etc." }, { "code": null, "e": 4831, "s": 4730, "text": "PROC ANOVA DATA = SASHELPS.CARS;\nCLASS type;\nMODEL horsepower = type;\nMEANS type / tukey lines;\nRUN;" }, { "code": null, "e": 4894, "s": 4831, "text": "When the above code is executed, we get the following result −" }, { "code": null, "e": 4929, "s": 4894, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4946, "s": 4929, "text": " Code And Create" }, { "code": null, "e": 4981, "s": 4946, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 4994, "s": 4981, "text": " Juan Galvan" }, { "code": null, "e": 5031, "s": 4994, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 5051, "s": 5031, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5086, "s": 5051, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5099, "s": 5086, "text": " Ermin Dedic" }, { "code": null, "e": 5136, "s": 5099, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 5152, "s": 5136, "text": " Muslim Helalee" }, { "code": null, "e": 5159, "s": 5152, "text": " Print" }, { "code": null, "e": 5170, "s": 5159, "text": " Add Notes" } ]
mysql_secure_installation - Improve MySQL Installation Security
Let us understand the MySQL installation related program mysql_secure_installation − This program enables the user to improve the security of their MySQL installation in the below mentioned ways: This program enables the user to improve the security of their MySQL installation in the below mentioned ways: The user can set a password for root accounts. The user can set a password for root accounts. The user can remove root accounts which are accessible from outside the local host. The user can remove root accounts which are accessible from outside the local host. The user can remove anonymous-user accounts. The user can remove anonymous-user accounts. The user can remove the test database which, by default, can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_. The user can remove the test database which, by default, can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_. The mysql_secure_installation helps the user to implement security recommendations. The mysql_secure_installation helps the user to implement security recommendations. Normal usage is to connect to the local MySQL server, then invoke mysql_secure_installation without arguments. The example has been shown below − shell> mysql_secure_installation When the above statement is executed, mysql_secure_installation prompts the user to determine which actions need to be performed. Most of the usual MySQL client options like --host and --port can be used on the command line and in the option files. Let us take an example − To connect to the local server over IPv6 using port 3307, the below command can be used − shell> mysql_secure_installation --host=::1 --port=3307 The mysql_secure_installation supports the below options and can be specified on the command line or in the [mysql_secure_installation] and [client] groups of an option file. --host=host_name, -h host_name It helps connect to the MySQL server on the given host. --no-defaults It doesn’t read any option files. If program startup fails due to reading unknown options from an option file, --no-defaults option can be used to prevent them from being read. --help, -? It helps display a help message and exit. --use-default It is used to execute noninteractively. This option can be used for unattended installation operations. --user=user_name, -u user_name It is the user name of the MySQL account to be used to connect to the server.
[ { "code": null, "e": 1147, "s": 1062, "text": "Let us understand the MySQL installation related program mysql_secure_installation −" }, { "code": null, "e": 1258, "s": 1147, "text": "This program enables the user to improve the security of their MySQL installation in the below mentioned ways:" }, { "code": null, "e": 1369, "s": 1258, "text": "This program enables the user to improve the security of their MySQL installation in the below mentioned ways:" }, { "code": null, "e": 1416, "s": 1369, "text": "The user can set a password for root accounts." }, { "code": null, "e": 1463, "s": 1416, "text": "The user can set a password for root accounts." }, { "code": null, "e": 1547, "s": 1463, "text": "The user can remove root accounts which are accessible from outside the local host." }, { "code": null, "e": 1631, "s": 1547, "text": "The user can remove root accounts which are accessible from outside the local host." }, { "code": null, "e": 1676, "s": 1631, "text": "The user can remove anonymous-user accounts." }, { "code": null, "e": 1721, "s": 1676, "text": "The user can remove anonymous-user accounts." }, { "code": null, "e": 1919, "s": 1721, "text": "The user can remove the test database which, by default, can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_." }, { "code": null, "e": 2117, "s": 1919, "text": "The user can remove the test database which, by default, can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_." }, { "code": null, "e": 2201, "s": 2117, "text": "The mysql_secure_installation helps the user to implement security recommendations." }, { "code": null, "e": 2285, "s": 2201, "text": "The mysql_secure_installation helps the user to implement security recommendations." }, { "code": null, "e": 2431, "s": 2285, "text": "Normal usage is to connect to the local MySQL server, then invoke mysql_secure_installation without arguments. The example has been shown below −" }, { "code": null, "e": 2464, "s": 2431, "text": "shell> mysql_secure_installation" }, { "code": null, "e": 2594, "s": 2464, "text": "When the above statement is executed, mysql_secure_installation prompts the user to determine which actions need to be performed." }, { "code": null, "e": 2738, "s": 2594, "text": "Most of the usual MySQL client options like --host and --port can be used on the command line and in the option files. Let us take an example −" }, { "code": null, "e": 2828, "s": 2738, "text": "To connect to the local server over IPv6 using port 3307, the below command can be used −" }, { "code": null, "e": 2884, "s": 2828, "text": "shell> mysql_secure_installation --host=::1 --port=3307" }, { "code": null, "e": 3059, "s": 2884, "text": "The mysql_secure_installation supports the below options and can be specified on the command line or in the [mysql_secure_installation] and [client] groups of an option file." }, { "code": null, "e": 3090, "s": 3059, "text": "--host=host_name, -h host_name" }, { "code": null, "e": 3146, "s": 3090, "text": "It helps connect to the MySQL server on the given host." }, { "code": null, "e": 3160, "s": 3146, "text": "--no-defaults" }, { "code": null, "e": 3337, "s": 3160, "text": "It doesn’t read any option files. If program startup fails due to reading unknown options from an option file, --no-defaults option can be used to prevent them from being read." }, { "code": null, "e": 3348, "s": 3337, "text": "--help, -?" }, { "code": null, "e": 3390, "s": 3348, "text": "It helps display a help message and exit." }, { "code": null, "e": 3404, "s": 3390, "text": "--use-default" }, { "code": null, "e": 3508, "s": 3404, "text": "It is used to execute noninteractively. This option can be used for unattended installation operations." }, { "code": null, "e": 3539, "s": 3508, "text": "--user=user_name, -u user_name" }, { "code": null, "e": 3617, "s": 3539, "text": "It is the user name of the MySQL account to be used to connect to the server." } ]
How to use Deep Learning for Time Series Forecasting | by Christophe Pere | Towards Data Science
For a long time, I heard that the problem of time series could only be approached by statistical methods (AR[1], AM[2], ARMA[3], ARIMA[4]). These techniques are generally used by mathematicians who try to improve them continuously to constrain stationary and non-stationary time series. A friend of mine (mathematician, professor of statistics, and specialist in non-stationary time series) offered me several months ago to work on the validation and improvement of techniques to reconstruct the lightcurve of stars. Indeed, the Kepler satellite[11], like many other satellites, could not continuously measure the intensity of the luminous flux of nearby stars. The Kepler satellite was dedicated between 2009 and 2016 to search for planets outside our Solar System called extrasolar planets or exoplanets. As you have understood, we are going to travel a little further than our planet Earth and deep dive into a galactic journey whose machine learning will be our vessel. As you can understand, astrophysics has remained a strong passion for me. The notebook is available on Github: Here. So what ship will we carry through this study? We will use the recurrent neural networks (RNN[5]), models. We will use LSTM[6], GRU[7], Stacked LSTM, Stacked GRU, Bidirectional[8] LSTM, Bidirectional GRU, and also CNN-LSTM[9]. For those passionate about tree family, you can find a great article on XGBoost and time series written by Jason Brownlee here. A great repository about time series is available on github. For those who are not familiar with the RNN family, see them as learning methods with memory effect and the ability to forget. The bidirectional term comes from the architecture, it is about two RNN which will "read" the data in one direction (from left to right) and the other (from right to left) in order to be able to have the best representation of long-term dependencies. As said earlier in the introduction, the data correspond to flux measurements of several stars. Indeed, at each temporal increment (hour), the satellite made a measurement of the flux coming from nearby stars. This flux, or magnitude, which is light intensity, varies over time. There are several reasons for this, the proper movement of the satellite, rotation, angle of sight, etc. will vary. Therefore the number of photons measured will change, the star is a ball of molten material (hydrogen and helium fusion) which has its own movement therefore the emission of photons is made depending on its movement. This corresponds to fluctuations in light intensity. But, there can also be planets, exoplanets, which disturb the star or even pass between the star and in the line of sight of the satellite (transit method[12]). This passage obscures the star, the satellite receives fewer photons because they are blocked by the planet passing in front of it (a concrete example is a Solar eclipse due to the Moon). The set of flux measurements is called a light curve. What does a light curve look like? Here are some examples: The fluxes are very different from one star to another. Some are very noisy while others have great stability. The fluxes nevertheless present anomalies. Holes, or lack of measurement, are visible in the light curves. The goal is to see if it is possible to predict the behavior of light curves where there is no measurement. In order to be able to use the data in the models, it is necessary to carry out a data reduction. Two will be presented here, the moving average and window method. Moving average: The moving average consists of taking X successive points and compute the mean on them. This method permits to reduce the variability and delete the noise. This also reduces the number of points, it’s a downsampling method. The following function allows us to compute a moving average from a list of points by giving a number that will be used to compute the average and the standard deviation of the points. You can see that the function takes 3 parameters in the input. time and flux are the x and y of the time series. lag is the parameter controlling the number of points takes into account to compute the mean of the time and flux and the standard deviation of the flux. Now, we can take a look at how to use this function and the result obtained by the transformation. # import the packages needed for the studymatplotlib inlineimport scipyimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport sklearnimport tensorflow as tf# let's see the progress barfrom tqdm import tqdmtqdm().pandas() Now we need to import the data. The file kep_lightcurves.csv contains the data from the 13 stars. Each star has 4 columns, the original flux (‘..._orig’), the rescaled flux is the original flux minus the average flux (‘..._rscl’), the difference (‘..._diff’), and the residuals (‘..._res’). So, 52 columns in total. # reduce the number of points with the mean on 20 pointsx, y, y_err = moving_mean(df.index,df["001724719_rscl"], 20) df.index correspond to the time of the time seriesdf[“001724719_rscl”] rescaled flux of the star (“001724719”)lag=20 is the number of points where the mean and the std will be computed The result for the 3 previous lightcurves: Window Method: The second method is the window method, how does it work? You need to take a number of points, in the previous case 20, compute the mean (no difference with the previous method), this point it’s the beginning of the new time series and it is at the position 20 (shift of 19 points). But, instead of shifting to the next 20 points, the window is shifted by one point, compute the mean with the 20 previous points and move again and again by just shifting one step ahead. It’s not a downsampling method but a cleaning method because the effect is to smooth the data points. Let’s see it in code: You can easily use it like that: # reduce the number of points with the mean on 20 pointsx, y, y_err = mean_sliding_windows(df.index,df["001724719_rscl"], 40) df.index correspond to the time of the time seriesdf[“001724719_rscl”] rescaled flux of the star (“001724719”)lag=40 is the number of points where the mean and the std will be computed Now, look at the result: Well, not so bad. Setting the lag to 40 permits to “predict” or extend the new time series in the small holes. But, if you look closer you’ll see a divergence at the beginning and the end of the portions of the red line. The function can be improved to avoid these artifacts. For the rest of the study, we will use the time series obtained with the moving average method. Change the x-axis from values to dates: You can change the axis if you want with dates. The Kepler mission began on 2009–03–07 and ended in 2017. Pandas has a function called pd.data_range() this function that allows you to create dates from a list constantly incrementing. df.index = pd.date_range(‘2009–03–07’, periods=len(df.index), freq=’h’) This line of code will create a new index with a frequency of hours. If you print the result (as below) you’ll find a proper real timescale. $ df.indexDatetimeIndex(['2009-03-07 00:00:00', '2009-03-07 01:00:00', '2009-03-07 02:00:00', '2009-03-07 03:00:00', '2009-03-07 04:00:00', '2009-03-07 05:00:00', '2009-03-07 06:00:00', '2009-03-07 07:00:00', '2009-03-07 08:00:00', '2009-03-07 09:00:00', ... '2017-04-29 17:00:00', '2017-04-29 18:00:00', '2017-04-29 19:00:00', '2017-04-29 20:00:00', '2017-04-29 21:00:00', '2017-04-29 22:00:00', '2017-04-29 23:00:00', '2017-04-30 00:00:00', '2017-04-30 01:00:00', '2017-04-30 02:00:00'], dtype='datetime64[ns]', length=71427, freq='H') You have now a good timescale for the original time series. Generate the datasets So, now that the data reduction functions have been created, we can combine them in another function (shown below) which will take into account the initial dataset and the name of the stars present in the dataset (this part could have been done in the function). To generate the new data frames do this: stars = df.columnsstars = list(set([i.split("_")[0] for i in stars]))print(f"The number of stars available is: {len(stars)}")> The number of stars available is: 13 We have 13 stars with 4 data types, corresponding to 52 columns. df_mean, df_slide = reduced_data(df,stars) Perfect, at this point, you have two new datasets containing the data reduced by the moving average and the window method. Prepare the data: In order to use a machine-learning algorithm to predict time series, the data must be prepared accordingly. The data cannot just be set at (x,y) data points. The data must take the form of a series [x1, x2, x3, ..., xn] and a predicted value y. The function below shows you how to set up your dataset: Two important things before starting. 1- The data need to be rescaledDeep Learning algorithms are better when the data is in the range of [0, 1) to predict time series. To do it simply scikit-learn provides the function MinMaxScaler(). You can configure the feature_range parameter but by default it takes (0, 1). And clean the data of nan values (if you don’t delete the nan values your loss function will be output nan). # normalize the dataset num = 2 # choose the third star in the datasetvalues = df_model[stars[num]+"_rscl_y"].values # extract the list of valuesscaler = MinMaxScaler(feature_range=(0, 1)) # make an instance of MinMaxScalerdataset = scaler.fit_transform(values[~np.isnan(values)].reshape(-1, 1)) # the data will be clean of nan values, rescaled and reshape 2- The data need to be converted into x list and y Now, we will the create_values() function to generate the data for the models. But, before, I prefer to save the original data by: df_model = df_mean.save() # split into train and test setstrain_size = int(len(dataset) * 0.8) # make 80% data traintrain = dataset[:train_size] # set the train datatest = dataset[train_size:] # set the test data # reshape into X=t and Y=t+1look_back = 20trainX, trainY = create_dataset(train, look_back)testX, testY = create_dataset(test, look_back)# reshape input to be [samples, time steps, features]trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1)) Just take a look at the result: trainX[0]> array([[0.7414906], [0.76628096], [0.79901113], [0.62779976], [0.64012722], [0.64934765], [0.68549234], [0.64054092], [0.68075644], [0.73782449], [0.68319294], [0.64330245], [0.61339268], [0.62758265], [0.61779702], [0.69994317], [0.64737128], [0.64122564], [0.62016833], [0.47867125]]) # 20 values in the first value of x train datatrainY[0]> array([0.46174275]) # the corresponding y value Metrics What metrics do we use for time series prediction? We can use the mean absolute error and the mean squared error. They are given by the function: You need to first import the functions: from sklearn.metrics import mean_absolute_error, mean_squared_error RNNs: You can implement easily the RNN family with Keras in few lines of code. Here you can use this function which will configure your RNN. You need to first import the different models from Keras like: # import some packagesimport tensorflow as tffrom keras.layers import SimpleRNN, LSTM, GRU, Bidirectional, Conv1D, MaxPooling1D, Dropout Now, we have the models imported from Keras. The function below can generate a simple model (SimpleRNN, LSTM, GRU). Or, two models (identical) can be stacked, or used in Bidirectional or a stack of two Bidirectional models. You can also add the CNN part (Conv1D)with MaxPooling1D and dropout. This function computes the metrics for the training part and the test part and returned the results in a data frame. Look at how you how to use it for five examples. LSTM: # train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20)# plot the resuts of the prediction> plotting_predictions(dataset, look_back, x_train_predict_lstm, x_test_predict_lstm)# save the metrics per model in the dataframe df_results> df_results = df_results.append(res) GRU: # train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=GRU, unit=12, look_back=20) Stack LSTM: # train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, stacked=True) Bidirectional LSTM: # train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, bidirection=True) CNN-LSTM: # train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, cnn=True) The results are pretty good considering the data. We can see that deep learning RNN can reproduce with good accuracy of the data. The figure below shows the result of the prediction by the LSTM model. Table 1: Results of the different RNN models, showing the MAE and MSE metrics Name | MAE Train | MSE Train | MAE Test | MSE Test-------------------------------------------------------------------- GRU | 4.24 | 34.11 | 4.15 | 31.47 LSTM | 4.26 | 34.54 | 4.16 | 31.64 Stack_GRU | 4.19 | 33.89 | 4.17 | 32.01 SimpleRNN | 4.21 | 34.07 | 4.18 | 32.41 LSTM | 4.28 | 35.1 | 4.21 | 31.9 Bi_GRU | 4.21 | 34.34 | 4.22 | 32.54 Stack_Bi_LSTM | 4.45 | 36.83 | 4.24 | 32.22 Bi_LSTM | 4.31 | 35.37 | 4.27 | 32.4Stack_SimpleRNN | 4.4 | 35.62 | 4.27 | 33.94 SimpleRNN | 4.44 | 35.94 | 4.31 | 34.37 Stack_LSTM | 4.51 | 36.78 | 4.4 | 34.28 Stacked_Bi_GRU | 4.56 | 37.32 | 4.45 | 35.34 CNN_LSTM | 5.01 | 45.85 | 4.55 | 36.29 CNN_GRU | 5.05 | 46.25 | 4.66 | 37.17 CNN_Stack_GRU | 5.07 | 45.92 | 4.7 | 38.64 The Table 1 shows the mean absolute error (MAE) and the mean squared error (MSE) for the train set and the test set for the RNN family. The GRU shows the best result on the test set with an MAE of 4.15 and an MSE of 31.47. The results are good and reproduced the lightcurves of the different stars (see notebook). However, the fluctuations are not perfectly reproduced, the peaks do not have the same intensity and the flux is slightly shifted. A potential correction could be made via the attention mechanisms (Transformers[10]). Another way is to tune the models, the number of layers (stack), the number of units (cells), the combination of different RNN algorithms, new loss function or activation function, etc. This article shows the possibilities of combining so-called artificial intelligence methods with time series. The power of memory algorithms (RNN, LSTM, GRU) makes it possible to accurately reproduce sporadic fluctuations of events. In our case, the stellar flux exhibited quite strong and marked fluctuations that the methods have been able to capture. This study shows that time series are no longer reserved for statistical methods such as the ARIMA[4] model. [1] Autoregressive model, Wikipedia[2] Moving-average model, Wikipedia[3] Peter Whittle, 1950. Hypothesis testing in time series analysis. Thesis[4] Alberto Luceño & Daniel Peña, 2008. Autoregressive Integrated Moving Average (ARIMA) Modeling. Wiley Online Library. https://doi.org/10.1002/9780470061572.eqr276[5] Rumelhart, David E. et al., 1986. Learning representations by back-propagating errors. Nature. 323 (6088): 533–536. 1986Natur.323..533R. [6] Hochreiter, Sepp & Schmidhuber, Jürgen, 1997. Long Short-Term Memory. Neural Computation. 9 (8): 1735–1780. doi:10.1162/neco.1997.9.8.1735[7] Cho, KyungHyun et al., 2014. Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling. arXiv:1412.3555[8] M. Schuster & K.K. Paliwal, 1997. Bidirectional recurrent neural networks. IEEE Transactions on Signal Processing, Volume: 45 , Issue: 11, pp. 2673–2681. DOI: 10.1109/78.650093[9] Tara N. Sainath et al., 2014. CONVOLUTIONAL, LONG SHORT-TERM MEMORY,FULLY CONNECTED DEEP NEURAL NETWORKS. https://static.googleusercontent.com/media/research.google.com/fr//pubs/archive/43455.pdf[10] Ashish Vaswani et al., 2017. Attention is all you need. https://arxiv.org/abs/1706.03762[11] Kepler mission, Nasa
[ { "code": null, "e": 459, "s": 172, "text": "For a long time, I heard that the problem of time series could only be approached by statistical methods (AR[1], AM[2], ARMA[3], ARIMA[4]). These techniques are generally used by mathematicians who try to improve them continuously to constrain stationary and non-stationary time series." }, { "code": null, "e": 979, "s": 459, "text": "A friend of mine (mathematician, professor of statistics, and specialist in non-stationary time series) offered me several months ago to work on the validation and improvement of techniques to reconstruct the lightcurve of stars. Indeed, the Kepler satellite[11], like many other satellites, could not continuously measure the intensity of the luminous flux of nearby stars. The Kepler satellite was dedicated between 2009 and 2016 to search for planets outside our Solar System called extrasolar planets or exoplanets." }, { "code": null, "e": 1220, "s": 979, "text": "As you have understood, we are going to travel a little further than our planet Earth and deep dive into a galactic journey whose machine learning will be our vessel. As you can understand, astrophysics has remained a strong passion for me." }, { "code": null, "e": 1263, "s": 1220, "text": "The notebook is available on Github: Here." }, { "code": null, "e": 1679, "s": 1263, "text": "So what ship will we carry through this study? We will use the recurrent neural networks (RNN[5]), models. We will use LSTM[6], GRU[7], Stacked LSTM, Stacked GRU, Bidirectional[8] LSTM, Bidirectional GRU, and also CNN-LSTM[9]. For those passionate about tree family, you can find a great article on XGBoost and time series written by Jason Brownlee here. A great repository about time series is available on github." }, { "code": null, "e": 2057, "s": 1679, "text": "For those who are not familiar with the RNN family, see them as learning methods with memory effect and the ability to forget. The bidirectional term comes from the architecture, it is about two RNN which will \"read\" the data in one direction (from left to right) and the other (from right to left) in order to be able to have the best representation of long-term dependencies." }, { "code": null, "e": 2722, "s": 2057, "text": "As said earlier in the introduction, the data correspond to flux measurements of several stars. Indeed, at each temporal increment (hour), the satellite made a measurement of the flux coming from nearby stars. This flux, or magnitude, which is light intensity, varies over time. There are several reasons for this, the proper movement of the satellite, rotation, angle of sight, etc. will vary. Therefore the number of photons measured will change, the star is a ball of molten material (hydrogen and helium fusion) which has its own movement therefore the emission of photons is made depending on its movement. This corresponds to fluctuations in light intensity." }, { "code": null, "e": 3071, "s": 2722, "text": "But, there can also be planets, exoplanets, which disturb the star or even pass between the star and in the line of sight of the satellite (transit method[12]). This passage obscures the star, the satellite receives fewer photons because they are blocked by the planet passing in front of it (a concrete example is a Solar eclipse due to the Moon)." }, { "code": null, "e": 3184, "s": 3071, "text": "The set of flux measurements is called a light curve. What does a light curve look like? Here are some examples:" }, { "code": null, "e": 3510, "s": 3184, "text": "The fluxes are very different from one star to another. Some are very noisy while others have great stability. The fluxes nevertheless present anomalies. Holes, or lack of measurement, are visible in the light curves. The goal is to see if it is possible to predict the behavior of light curves where there is no measurement." }, { "code": null, "e": 3674, "s": 3510, "text": "In order to be able to use the data in the models, it is necessary to carry out a data reduction. Two will be presented here, the moving average and window method." }, { "code": null, "e": 3690, "s": 3674, "text": "Moving average:" }, { "code": null, "e": 3914, "s": 3690, "text": "The moving average consists of taking X successive points and compute the mean on them. This method permits to reduce the variability and delete the noise. This also reduces the number of points, it’s a downsampling method." }, { "code": null, "e": 4099, "s": 3914, "text": "The following function allows us to compute a moving average from a list of points by giving a number that will be used to compute the average and the standard deviation of the points." }, { "code": null, "e": 4366, "s": 4099, "text": "You can see that the function takes 3 parameters in the input. time and flux are the x and y of the time series. lag is the parameter controlling the number of points takes into account to compute the mean of the time and flux and the standard deviation of the flux." }, { "code": null, "e": 4465, "s": 4366, "text": "Now, we can take a look at how to use this function and the result obtained by the transformation." }, { "code": null, "e": 4706, "s": 4465, "text": "# import the packages needed for the studymatplotlib inlineimport scipyimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport sklearnimport tensorflow as tf# let's see the progress barfrom tqdm import tqdmtqdm().pandas()" }, { "code": null, "e": 5022, "s": 4706, "text": "Now we need to import the data. The file kep_lightcurves.csv contains the data from the 13 stars. Each star has 4 columns, the original flux (‘..._orig’), the rescaled flux is the original flux minus the average flux (‘..._rscl’), the difference (‘..._diff’), and the residuals (‘..._res’). So, 52 columns in total." }, { "code": null, "e": 5140, "s": 5022, "text": "# reduce the number of points with the mean on 20 pointsx, y, y_err = moving_mean(df.index,df[\"001724719_rscl\"], 20)" }, { "code": null, "e": 5325, "s": 5140, "text": "df.index correspond to the time of the time seriesdf[“001724719_rscl”] rescaled flux of the star (“001724719”)lag=20 is the number of points where the mean and the std will be computed" }, { "code": null, "e": 5368, "s": 5325, "text": "The result for the 3 previous lightcurves:" }, { "code": null, "e": 5383, "s": 5368, "text": "Window Method:" }, { "code": null, "e": 5441, "s": 5383, "text": "The second method is the window method, how does it work?" }, { "code": null, "e": 5955, "s": 5441, "text": "You need to take a number of points, in the previous case 20, compute the mean (no difference with the previous method), this point it’s the beginning of the new time series and it is at the position 20 (shift of 19 points). But, instead of shifting to the next 20 points, the window is shifted by one point, compute the mean with the 20 previous points and move again and again by just shifting one step ahead. It’s not a downsampling method but a cleaning method because the effect is to smooth the data points." }, { "code": null, "e": 5977, "s": 5955, "text": "Let’s see it in code:" }, { "code": null, "e": 6010, "s": 5977, "text": "You can easily use it like that:" }, { "code": null, "e": 6137, "s": 6010, "text": "# reduce the number of points with the mean on 20 pointsx, y, y_err = mean_sliding_windows(df.index,df[\"001724719_rscl\"], 40)" }, { "code": null, "e": 6322, "s": 6137, "text": "df.index correspond to the time of the time seriesdf[“001724719_rscl”] rescaled flux of the star (“001724719”)lag=40 is the number of points where the mean and the std will be computed" }, { "code": null, "e": 6347, "s": 6322, "text": "Now, look at the result:" }, { "code": null, "e": 6623, "s": 6347, "text": "Well, not so bad. Setting the lag to 40 permits to “predict” or extend the new time series in the small holes. But, if you look closer you’ll see a divergence at the beginning and the end of the portions of the red line. The function can be improved to avoid these artifacts." }, { "code": null, "e": 6719, "s": 6623, "text": "For the rest of the study, we will use the time series obtained with the moving average method." }, { "code": null, "e": 6759, "s": 6719, "text": "Change the x-axis from values to dates:" }, { "code": null, "e": 6993, "s": 6759, "text": "You can change the axis if you want with dates. The Kepler mission began on 2009–03–07 and ended in 2017. Pandas has a function called pd.data_range() this function that allows you to create dates from a list constantly incrementing." }, { "code": null, "e": 7065, "s": 6993, "text": "df.index = pd.date_range(‘2009–03–07’, periods=len(df.index), freq=’h’)" }, { "code": null, "e": 7206, "s": 7065, "text": "This line of code will create a new index with a frequency of hours. If you print the result (as below) you’ll find a proper real timescale." }, { "code": null, "e": 7897, "s": 7206, "text": "$ df.indexDatetimeIndex(['2009-03-07 00:00:00', '2009-03-07 01:00:00', '2009-03-07 02:00:00', '2009-03-07 03:00:00', '2009-03-07 04:00:00', '2009-03-07 05:00:00', '2009-03-07 06:00:00', '2009-03-07 07:00:00', '2009-03-07 08:00:00', '2009-03-07 09:00:00', ... '2017-04-29 17:00:00', '2017-04-29 18:00:00', '2017-04-29 19:00:00', '2017-04-29 20:00:00', '2017-04-29 21:00:00', '2017-04-29 22:00:00', '2017-04-29 23:00:00', '2017-04-30 00:00:00', '2017-04-30 01:00:00', '2017-04-30 02:00:00'], dtype='datetime64[ns]', length=71427, freq='H')" }, { "code": null, "e": 7957, "s": 7897, "text": "You have now a good timescale for the original time series." }, { "code": null, "e": 7979, "s": 7957, "text": "Generate the datasets" }, { "code": null, "e": 8242, "s": 7979, "text": "So, now that the data reduction functions have been created, we can combine them in another function (shown below) which will take into account the initial dataset and the name of the stars present in the dataset (this part could have been done in the function)." }, { "code": null, "e": 8283, "s": 8242, "text": "To generate the new data frames do this:" }, { "code": null, "e": 8447, "s": 8283, "text": "stars = df.columnsstars = list(set([i.split(\"_\")[0] for i in stars]))print(f\"The number of stars available is: {len(stars)}\")> The number of stars available is: 13" }, { "code": null, "e": 8512, "s": 8447, "text": "We have 13 stars with 4 data types, corresponding to 52 columns." }, { "code": null, "e": 8555, "s": 8512, "text": "df_mean, df_slide = reduced_data(df,stars)" }, { "code": null, "e": 8678, "s": 8555, "text": "Perfect, at this point, you have two new datasets containing the data reduced by the moving average and the window method." }, { "code": null, "e": 8696, "s": 8678, "text": "Prepare the data:" }, { "code": null, "e": 8941, "s": 8696, "text": "In order to use a machine-learning algorithm to predict time series, the data must be prepared accordingly. The data cannot just be set at (x,y) data points. The data must take the form of a series [x1, x2, x3, ..., xn] and a predicted value y." }, { "code": null, "e": 8998, "s": 8941, "text": "The function below shows you how to set up your dataset:" }, { "code": null, "e": 9036, "s": 8998, "text": "Two important things before starting." }, { "code": null, "e": 9421, "s": 9036, "text": "1- The data need to be rescaledDeep Learning algorithms are better when the data is in the range of [0, 1) to predict time series. To do it simply scikit-learn provides the function MinMaxScaler(). You can configure the feature_range parameter but by default it takes (0, 1). And clean the data of nan values (if you don’t delete the nan values your loss function will be output nan)." }, { "code": null, "e": 9778, "s": 9421, "text": "# normalize the dataset num = 2 # choose the third star in the datasetvalues = df_model[stars[num]+\"_rscl_y\"].values # extract the list of valuesscaler = MinMaxScaler(feature_range=(0, 1)) # make an instance of MinMaxScalerdataset = scaler.fit_transform(values[~np.isnan(values)].reshape(-1, 1)) # the data will be clean of nan values, rescaled and reshape" }, { "code": null, "e": 9960, "s": 9778, "text": "2- The data need to be converted into x list and y Now, we will the create_values() function to generate the data for the models. But, before, I prefer to save the original data by:" }, { "code": null, "e": 9986, "s": 9960, "text": "df_model = df_mean.save()" }, { "code": null, "e": 10495, "s": 9986, "text": "# split into train and test setstrain_size = int(len(dataset) * 0.8) # make 80% data traintrain = dataset[:train_size] # set the train datatest = dataset[train_size:] # set the test data # reshape into X=t and Y=t+1look_back = 20trainX, trainY = create_dataset(train, look_back)testX, testY = create_dataset(test, look_back)# reshape input to be [samples, time steps, features]trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))" }, { "code": null, "e": 10527, "s": 10495, "text": "Just take a look at the result:" }, { "code": null, "e": 11044, "s": 10527, "text": "trainX[0]> array([[0.7414906], [0.76628096], [0.79901113], [0.62779976], [0.64012722], [0.64934765], [0.68549234], [0.64054092], [0.68075644], [0.73782449], [0.68319294], [0.64330245], [0.61339268], [0.62758265], [0.61779702], [0.69994317], [0.64737128], [0.64122564], [0.62016833], [0.47867125]]) # 20 values in the first value of x train datatrainY[0]> array([0.46174275]) # the corresponding y value" }, { "code": null, "e": 11052, "s": 11044, "text": "Metrics" }, { "code": null, "e": 11198, "s": 11052, "text": "What metrics do we use for time series prediction? We can use the mean absolute error and the mean squared error. They are given by the function:" }, { "code": null, "e": 11238, "s": 11198, "text": "You need to first import the functions:" }, { "code": null, "e": 11306, "s": 11238, "text": "from sklearn.metrics import mean_absolute_error, mean_squared_error" }, { "code": null, "e": 11312, "s": 11306, "text": "RNNs:" }, { "code": null, "e": 11510, "s": 11312, "text": "You can implement easily the RNN family with Keras in few lines of code. Here you can use this function which will configure your RNN. You need to first import the different models from Keras like:" }, { "code": null, "e": 11647, "s": 11510, "text": "# import some packagesimport tensorflow as tffrom keras.layers import SimpleRNN, LSTM, GRU, Bidirectional, Conv1D, MaxPooling1D, Dropout" }, { "code": null, "e": 11940, "s": 11647, "text": "Now, we have the models imported from Keras. The function below can generate a simple model (SimpleRNN, LSTM, GRU). Or, two models (identical) can be stacked, or used in Bidirectional or a stack of two Bidirectional models. You can also add the CNN part (Conv1D)with MaxPooling1D and dropout." }, { "code": null, "e": 12106, "s": 11940, "text": "This function computes the metrics for the training part and the test part and returned the results in a data frame. Look at how you how to use it for five examples." }, { "code": null, "e": 12112, "s": 12106, "text": "LSTM:" }, { "code": null, "e": 12543, "s": 12112, "text": "# train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20)# plot the resuts of the prediction> plotting_predictions(dataset, look_back, x_train_predict_lstm, x_test_predict_lstm)# save the metrics per model in the dataframe df_results> df_results = df_results.append(res)" }, { "code": null, "e": 12548, "s": 12543, "text": "GRU:" }, { "code": null, "e": 12763, "s": 12548, "text": "# train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=GRU, unit=12, look_back=20)" }, { "code": null, "e": 12775, "s": 12763, "text": "Stack LSTM:" }, { "code": null, "e": 13006, "s": 12775, "text": "# train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, stacked=True)" }, { "code": null, "e": 13026, "s": 13006, "text": "Bidirectional LSTM:" }, { "code": null, "e": 13261, "s": 13026, "text": "# train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, bidirection=True)" }, { "code": null, "e": 13271, "s": 13261, "text": "CNN-LSTM:" }, { "code": null, "e": 13498, "s": 13271, "text": "# train the model and compute the metrics> x_train_predict_lstm, y_train_lstm,x_test_predict_lstm, y_test_lstm, res= time_series_deep_learning(train_x, train_y, test_x, test_y, model_dl=LSTM , unit=12, look_back=20, cnn=True)" }, { "code": null, "e": 13699, "s": 13498, "text": "The results are pretty good considering the data. We can see that deep learning RNN can reproduce with good accuracy of the data. The figure below shows the result of the prediction by the LSTM model." }, { "code": null, "e": 13777, "s": 13699, "text": "Table 1: Results of the different RNN models, showing the MAE and MSE metrics" }, { "code": null, "e": 14809, "s": 13777, "text": " Name | MAE Train | MSE Train | MAE Test | MSE Test-------------------------------------------------------------------- GRU | 4.24 | 34.11 | 4.15 | 31.47 LSTM | 4.26 | 34.54 | 4.16 | 31.64 Stack_GRU | 4.19 | 33.89 | 4.17 | 32.01 SimpleRNN | 4.21 | 34.07 | 4.18 | 32.41 LSTM | 4.28 | 35.1 | 4.21 | 31.9 Bi_GRU | 4.21 | 34.34 | 4.22 | 32.54 Stack_Bi_LSTM | 4.45 | 36.83 | 4.24 | 32.22 Bi_LSTM | 4.31 | 35.37 | 4.27 | 32.4Stack_SimpleRNN | 4.4 | 35.62 | 4.27 | 33.94 SimpleRNN | 4.44 | 35.94 | 4.31 | 34.37 Stack_LSTM | 4.51 | 36.78 | 4.4 | 34.28 Stacked_Bi_GRU | 4.56 | 37.32 | 4.45 | 35.34 CNN_LSTM | 5.01 | 45.85 | 4.55 | 36.29 CNN_GRU | 5.05 | 46.25 | 4.66 | 37.17 CNN_Stack_GRU | 5.07 | 45.92 | 4.7 | 38.64" }, { "code": null, "e": 15032, "s": 14809, "text": "The Table 1 shows the mean absolute error (MAE) and the mean squared error (MSE) for the train set and the test set for the RNN family. The GRU shows the best result on the test set with an MAE of 4.15 and an MSE of 31.47." }, { "code": null, "e": 15526, "s": 15032, "text": "The results are good and reproduced the lightcurves of the different stars (see notebook). However, the fluctuations are not perfectly reproduced, the peaks do not have the same intensity and the flux is slightly shifted. A potential correction could be made via the attention mechanisms (Transformers[10]). Another way is to tune the models, the number of layers (stack), the number of units (cells), the combination of different RNN algorithms, new loss function or activation function, etc." }, { "code": null, "e": 15880, "s": 15526, "text": "This article shows the possibilities of combining so-called artificial intelligence methods with time series. The power of memory algorithms (RNN, LSTM, GRU) makes it possible to accurately reproduce sporadic fluctuations of events. In our case, the stellar flux exhibited quite strong and marked fluctuations that the methods have been able to capture." }, { "code": null, "e": 15989, "s": 15880, "text": "This study shows that time series are no longer reserved for statistical methods such as the ARIMA[4] model." } ]
Retail Management - Pricing
The bitterness of poor quality remains a long after low price is forgotten. − Leon M. Cautillo We as customers, often get to read advertisements from various retailers saying, “Quality product for right price!” This leads to following questions such as what is the right price and who sets it? What are the factors and strategies that determine the price for what we buy? The core capability of the retailers lies in pricing the products or services in a right manner to keep the customers happy, recover investment for production, and to generate revenue. The price at which the product is sold to the end customer is called the retail price of the product. Retail price is the summation of the manufacturing cost and all the costs that retailers incur at the time of charging the customer. Retail prices are affected by internal and external factors. Internal factors that influence retail prices include the following − Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor. Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor. The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price. The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price. Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products. Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products. Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price. Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price. Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments. Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments. External prices that influence retail prices include the following − Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high. Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high. Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price. Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price. Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product. Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product. Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less. Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less. Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices. Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices. The price charged is high if there is high demand for the product and low if the demand is low. The methods employed while pricing the product on the basis of demand are − Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time. Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time. Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100. Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100. Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration. Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration. Prestige Pricing − Pricing is done to convey quality of the product. Prestige Pricing − Pricing is done to convey quality of the product. Price Bundling − The offer of additional product or service is combined with the main product, together with special price. Price Bundling − The offer of additional product or service is combined with the main product, together with special price. A method of determining prices that takes a retail company’s profit objectives and production costs into account. These methods include the following − Cost plus Pricing − The company sets prices little above the manufacturing cost. For example, if the cost of a product is Rs. 600 per unit and the marketer expects 10 per cent profit, then the selling price is set to Rs. 660. Mark-up Pricing − The mark-ups are calculated as a percentage of the selling price and not as a percentage of the cost price. The formula used to determine the selling price is − Selling Price = Average unit cost/Selling price Break-even Pricing − The retail company determines the level of sales needed to cover all the relevant fixed and variable costs. They break-even when there is neither profit nor loss. For example, Fixed cost = Rs. 2, 00,000, Variable cost per unit = Rs. 15, and Selling price = Rs. 20. In this case, the company needs to sell (2,00, 000 / (20-15)) = 40,000 units to break even the fixed cost. Hence, the company may plan to sell at least 40,000 units to be profitable. If it is not possible, then it has to increase the selling price. The following formula is used to calculate the break-even point − Contribution = Selling price – Variable cost per unit Target Return Pricing − The retail company sets prices in order to achieve a particular Return On Investment (ROI). This can be calculated using the following formula − Target return price = Total costs + (Desired % ROI investment)/Total sales in units For example, Total investment = Rs. 10,000, Desired ROI = 20 per cent, Total cost = Rs.5000, and Total expected sales = 1,000 units Then the target return price will be Rs. 7 per unit as shown below − Target Return Price = (5000 + (20% * 10,000))/ 1000 = Rs. 7 This method ensures that the price exceeds all costs and contributes to profit. Early Cash Recovery Pricing − When market forecasts depict short life, it is essential for the price sensitive product segments such as fashion and technology to recover the investment. Sometimes the company anticipates the entry of a larger company in the market. In these cases, the companies price their products to shorten the risks and maximize short-term profit. When a retail company sets the prices for its product depending on how much the competitor is charging for a similar product, it is competition-oriented pricing. Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market. Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market. Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product. Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product. The company may charge different prices for the same product or service. Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers. Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers. Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year. Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year. Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats. Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats. 20 Lectures 3.5 hours Richa Maheshwari 44 Lectures 5.5 hours Navdeep Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 2091, "s": 2015, "text": "The bitterness of poor quality remains a long after low price is forgotten." }, { "code": null, "e": 2110, "s": 2091, "text": "− Leon M. Cautillo" }, { "code": null, "e": 2387, "s": 2110, "text": "We as customers, often get to read advertisements from various retailers saying, “Quality product for right price!” This leads to following questions such as what is the right price and who sets it? What are the factors and strategies that determine the price for what we buy?" }, { "code": null, "e": 2572, "s": 2387, "text": "The core capability of the retailers lies in pricing the products or services in a right manner to keep the customers happy, recover investment for production, and to generate revenue." }, { "code": null, "e": 2807, "s": 2572, "text": "The price at which the product is sold to the end customer is called the retail price of the product. Retail price is the summation of the manufacturing cost and all the costs that retailers incur at the time of charging the customer." }, { "code": null, "e": 2868, "s": 2807, "text": "Retail prices are affected by internal and external factors." }, { "code": null, "e": 2938, "s": 2868, "text": "Internal factors that influence retail prices include the following −" }, { "code": null, "e": 3268, "s": 2938, "text": "Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor." }, { "code": null, "e": 3598, "s": 3268, "text": "Manufacturing Cost − The retail company considers both, fixed and variable costs of manufacturing the product. The fixed costs does not vary depending upon the production volume. For example, property tax. The variable costs include varying costs of raw material and costs depending upon volume of production. For example, labor." }, { "code": null, "e": 3883, "s": 3598, "text": "The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price." }, { "code": null, "e": 4168, "s": 3883, "text": "The Predetermined Objectives − The objective of the retail company varies with time and market situations. If the objective is to increase return on investment, then the company may charge a higher price. If the objective is to increase market share, then it may charge a lower price." }, { "code": null, "e": 4363, "s": 4168, "text": "Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products." }, { "code": null, "e": 4558, "s": 4363, "text": "Image of the Firm − The retail company may consider its own image in the market. For example, companies with large goodwill such as Procter & Gamble can demand a higher price for their products." }, { "code": null, "e": 4872, "s": 4558, "text": "Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price." }, { "code": null, "e": 5186, "s": 4872, "text": "Product Status − The stage at which the product is in its product life cycle determines its price. At the time of introducing the product in the market, the company may charge lower price for it to attract new customers. When the product is accepted and established in the market, the company increases the price." }, { "code": null, "e": 5360, "s": 5186, "text": "Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments." }, { "code": null, "e": 5534, "s": 5360, "text": "Promotional Activity − If the company is spending high cost on advertising and sales promotion, then it keeps product price high in order to recover the cost of investments." }, { "code": null, "e": 5603, "s": 5534, "text": "External prices that influence retail prices include the following −" }, { "code": null, "e": 5772, "s": 5603, "text": "Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high." }, { "code": null, "e": 5941, "s": 5772, "text": "Competition − In case of high competition, the prices may be set low to face the competition effectively, and if there is less competition, the prices may be kept high." }, { "code": null, "e": 6091, "s": 5941, "text": "Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price." }, { "code": null, "e": 6241, "s": 6091, "text": "Buying Power of Consumers − The sensitivity of the customer towards price variation and purchasing power of the customer contribute to setting price." }, { "code": null, "e": 6390, "s": 6241, "text": "Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product." }, { "code": null, "e": 6539, "s": 6390, "text": "Government Policies − Government rules and regulation about manufacturing and announcement of administered prices can increase the price of product." }, { "code": null, "e": 6693, "s": 6539, "text": "Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less." }, { "code": null, "e": 6847, "s": 6693, "text": "Market Conditions − If market is under recession, the consumers buying pattern changes. To modify their buying behavior, the product prices are set less." }, { "code": null, "e": 7061, "s": 6847, "text": "Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices." }, { "code": null, "e": 7275, "s": 7061, "text": "Levels of Channels Involved − The retailer has to consider number of channels involved from manufacturing to retail and their expectations. The deeper the level of channels, the higher would be the product prices." }, { "code": null, "e": 7447, "s": 7275, "text": "The price charged is high if there is high demand for the product and low if the demand is low. The methods employed while pricing the product on the basis of demand are −" }, { "code": null, "e": 7592, "s": 7447, "text": "Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time." }, { "code": null, "e": 7737, "s": 7592, "text": "Price Skimming − Initially the product is charged at a high price that the customer is willing to pay and then it decreases gradually with time." }, { "code": null, "e": 7828, "s": 7737, "text": "Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100." }, { "code": null, "e": 7919, "s": 7828, "text": "Odd Even Pricing − The customers perceive prices like 99.99, 11.49 to be cheaper than 100." }, { "code": null, "e": 8033, "s": 7919, "text": "Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration." }, { "code": null, "e": 8147, "s": 8033, "text": "Penetration Pricing − Price is reduced to compete with other similar products to allow more customer penetration." }, { "code": null, "e": 8216, "s": 8147, "text": "Prestige Pricing − Pricing is done to convey quality of the product." }, { "code": null, "e": 8285, "s": 8216, "text": "Prestige Pricing − Pricing is done to convey quality of the product." }, { "code": null, "e": 8409, "s": 8285, "text": "Price Bundling − The offer of additional product or service is combined with the main product, together with special price." }, { "code": null, "e": 8533, "s": 8409, "text": "Price Bundling − The offer of additional product or service is combined with the main product, together with special price." }, { "code": null, "e": 8685, "s": 8533, "text": "A method of determining prices that takes a retail company’s profit objectives and production costs into account. These methods include the following −" }, { "code": null, "e": 8911, "s": 8685, "text": "Cost plus Pricing − The company sets prices little above the manufacturing cost. For example, if the cost of a product is Rs. 600 per unit and the marketer expects 10 per cent profit, then the selling price is set to Rs. 660." }, { "code": null, "e": 9037, "s": 8911, "text": "Mark-up Pricing − The mark-ups are calculated as a percentage of the selling price and not as a percentage of the cost price." }, { "code": null, "e": 9090, "s": 9037, "text": "The formula used to determine the selling price is −" }, { "code": null, "e": 9139, "s": 9090, "text": "Selling Price = Average unit cost/Selling price\n" }, { "code": null, "e": 9323, "s": 9139, "text": "Break-even Pricing − The retail company determines the level of sales needed to cover all the relevant fixed and variable costs. They break-even when there is neither profit nor loss." }, { "code": null, "e": 9425, "s": 9323, "text": "For example, Fixed cost = Rs. 2, 00,000, Variable cost per unit = Rs. 15, and Selling price = Rs. 20." }, { "code": null, "e": 9674, "s": 9425, "text": "In this case, the company needs to sell (2,00, 000 / (20-15)) = 40,000 units to break even the fixed cost. Hence, the company may plan to sell at least 40,000 units to be profitable. If it is not possible, then it has to increase the selling price." }, { "code": null, "e": 9740, "s": 9674, "text": "The following formula is used to calculate the break-even point −" }, { "code": null, "e": 9795, "s": 9740, "text": "Contribution = Selling price – Variable cost per unit\n" }, { "code": null, "e": 9911, "s": 9795, "text": "Target Return Pricing − The retail company sets prices in order to achieve a particular Return On Investment (ROI)." }, { "code": null, "e": 9964, "s": 9911, "text": "This can be calculated using the following formula −" }, { "code": null, "e": 10049, "s": 9964, "text": "Target return price = Total costs + (Desired % ROI investment)/Total sales in units\n" }, { "code": null, "e": 10093, "s": 10049, "text": "For example, Total investment = Rs. 10,000," }, { "code": null, "e": 10120, "s": 10093, "text": "Desired ROI = 20 per cent," }, { "code": null, "e": 10146, "s": 10120, "text": "Total cost = Rs.5000, and" }, { "code": null, "e": 10181, "s": 10146, "text": "Total expected sales = 1,000 units" }, { "code": null, "e": 10250, "s": 10181, "text": "Then the target return price will be Rs. 7 per unit as shown below −" }, { "code": null, "e": 10310, "s": 10250, "text": "Target Return Price = (5000 + (20% * 10,000))/ 1000 = Rs. 7" }, { "code": null, "e": 10390, "s": 10310, "text": "This method ensures that the price exceeds all costs and contributes to profit." }, { "code": null, "e": 10759, "s": 10390, "text": "Early Cash Recovery Pricing − When market forecasts depict short life, it is essential for the price sensitive product segments such as fashion and technology to recover the investment. Sometimes the company anticipates the entry of a larger company in the market. In these cases, the companies price their products to shorten the risks and maximize short-term profit." }, { "code": null, "e": 10921, "s": 10759, "text": "When a retail company sets the prices for its product depending on how much the competitor is charging for a similar product, it is competition-oriented pricing." }, { "code": null, "e": 11028, "s": 10921, "text": "Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market." }, { "code": null, "e": 11135, "s": 11028, "text": "Competitor’s Parity − The retail company may set the price as close as the giant competitor in the market." }, { "code": null, "e": 11247, "s": 11135, "text": "Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product." }, { "code": null, "e": 11359, "s": 11247, "text": "Discount Pricing − A product is priced at low cost if it is lacking some feature than the competitor’s product." }, { "code": null, "e": 11432, "s": 11359, "text": "The company may charge different prices for the same product or service." }, { "code": null, "e": 11670, "s": 11432, "text": "Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers." }, { "code": null, "e": 11908, "s": 11670, "text": "Customer Segment Pricing − The price is charged differently for customers from different customer segments. For example, customers who purchase online may be charged less as the cost of service is low for the segment of online customers." }, { "code": null, "e": 12092, "s": 11908, "text": "Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year." }, { "code": null, "e": 12276, "s": 12092, "text": "Time Pricing − The retailer charges price depending upon time, season, occasions, etc. For example, many resorts charge more for their vacation packages depending on the time of year." }, { "code": null, "e": 12462, "s": 12276, "text": "Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats." }, { "code": null, "e": 12648, "s": 12462, "text": "Location Pricing − The retailer charges the price depending on where the customer is located. For example, front-row seats of a drama theater are charged high price than rear-row seats." }, { "code": null, "e": 12683, "s": 12648, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12701, "s": 12683, "text": " Richa Maheshwari" }, { "code": null, "e": 12736, "s": 12701, "text": "\n 44 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12751, "s": 12736, "text": " Navdeep Yadav" }, { "code": null, "e": 12758, "s": 12751, "text": " Print" }, { "code": null, "e": 12769, "s": 12758, "text": " Add Notes" } ]
numpy.random.randn() in Python - GeeksforGeeks
28 Mar, 2022 The numpy.random.randn() function creates an array of specified shape and fills it with random values as per standard normal distribution. If positive arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the d_i are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.Syntax : numpy.random.randn(d0, d1, ..., dn) Parameters : d0, d1, ..., dn : [int, optional]Dimension of the returned array we require, If no argument is given a single Python float is returned. Return : Array of defined shape, filled with random floating-point samples from the standard normal distribution. Code 1 : randomly constructing 1D array Python3 # Python Program illustrating# numpy.random.randn() method import numpy as geek # 1D Arrayarray = geek.random.randn(5)print("1D Array filled with random values : \n", array); Output : 1D Array filled with random values : [-0.51733692 0.48813676 -0.88147002 1.12901958 0.68026197] Code 2 : randomly constructing 2D array Python3 # Python Program illustrating# numpy.random.randn() method import numpy as geek # 2D Array array = geek.random.randn(3, 4)print("2D Array filled with random values : \n", array); Output : 2D Array filled with random values : [[ 1.33262386 -0.88922967 -0.07056098 0.27340112] [ 1.00664965 -0.68443807 0.43801295 -0.35874714] [-0.19289416 -0.42746963 -1.80435223 0.02751727]] Code 3 : randomly constructing 3D array Python3 # Python Program illustrating# numpy.random.randn() method import numpy as geek # 3D Array array = geek.random.randn(2, 2 ,2)print("3D Array filled with random values : \n", array); Output : 3D Array filled with random values : [[[-0.00416587 -0.66211158] [-0.97254293 -0.68981333]] [[-0.18304476 -0.8371425 ] [ 2.18985366 -0.9740637 ]]] Code 4 : Manipulations with randomly created array Python3 # Python Program illustrating# numpy.random.randn() method import numpy as geek # 3D Array array = geek.random.randn(2, 2 ,2)print("3D Array filled with random values : \n", array); # Multiplying values with 3print("\nArray * 3 : \n", array *3) # Or we cab directly do so byarray = geek.random.randn(2, 2 ,2) * 3 + 2print("\nArray * 3 + 2 : \n", array); Output : 3D Array filled with random values : [[[ 1.9609643 -1.89882763] [ 0.52252173 0.08159455]] [[-0.6060213 -0.86759247] [ 0.53870235 -0.77388125]]] Array * 3 : [[[ 5.88289289 -5.69648288] [ 1.56756519 0.24478366]] [[-1.81806391 -2.6027774 ] [ 1.61610704 -2.32164376]]] Array * 3 + 2 : [[[-2.73766306 6.80761741] [-1.57909191 -1.64195796]] [[ 0.51019498 1.30017345] [ 3.8107863 -4.07438963]]] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.randn.htmlNote : These codes won’t run on online IDE’s. Please run them on your systems to explore the working. . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sumitgumber28 kothavvsaakash Python numpy-Random sampling Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24873, "s": 24845, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25399, "s": 24873, "text": "The numpy.random.randn() function creates an array of specified shape and fills it with random values as per standard normal distribution. If positive arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the d_i are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.Syntax : " }, { "code": null, "e": 25435, "s": 25399, "text": "numpy.random.randn(d0, d1, ..., dn)" }, { "code": null, "e": 25450, "s": 25435, "text": "Parameters : " }, { "code": null, "e": 25592, "s": 25450, "text": "d0, d1, ..., dn : [int, optional]Dimension of the returned array we require, \n If no argument is given a single Python float is returned." }, { "code": null, "e": 25603, "s": 25592, "text": "Return : " }, { "code": null, "e": 25709, "s": 25603, "text": "Array of defined shape, filled with random floating-point samples from \nthe standard normal distribution." }, { "code": null, "e": 25751, "s": 25709, "text": "Code 1 : randomly constructing 1D array " }, { "code": null, "e": 25759, "s": 25751, "text": "Python3" }, { "code": "# Python Program illustrating# numpy.random.randn() method import numpy as geek # 1D Arrayarray = geek.random.randn(5)print(\"1D Array filled with random values : \\n\", array);", "e": 25936, "s": 25759, "text": null }, { "code": null, "e": 25947, "s": 25936, "text": "Output : " }, { "code": null, "e": 26048, "s": 25947, "text": "1D Array filled with random values : \n [-0.51733692 0.48813676 -0.88147002 1.12901958 0.68026197]" }, { "code": null, "e": 26090, "s": 26048, "text": "Code 2 : randomly constructing 2D array " }, { "code": null, "e": 26098, "s": 26090, "text": "Python3" }, { "code": "# Python Program illustrating# numpy.random.randn() method import numpy as geek # 2D Array array = geek.random.randn(3, 4)print(\"2D Array filled with random values : \\n\", array);", "e": 26280, "s": 26098, "text": null }, { "code": null, "e": 26291, "s": 26280, "text": "Output : " }, { "code": null, "e": 26484, "s": 26291, "text": "2D Array filled with random values : \n [[ 1.33262386 -0.88922967 -0.07056098 0.27340112]\n [ 1.00664965 -0.68443807 0.43801295 -0.35874714]\n [-0.19289416 -0.42746963 -1.80435223 0.02751727]]" }, { "code": null, "e": 26526, "s": 26484, "text": "Code 3 : randomly constructing 3D array " }, { "code": null, "e": 26534, "s": 26526, "text": "Python3" }, { "code": "# Python Program illustrating# numpy.random.randn() method import numpy as geek # 3D Array array = geek.random.randn(2, 2 ,2)print(\"3D Array filled with random values : \\n\", array);", "e": 26721, "s": 26534, "text": null }, { "code": null, "e": 26732, "s": 26721, "text": "Output : " }, { "code": null, "e": 26887, "s": 26732, "text": "3D Array filled with random values : \n [[[-0.00416587 -0.66211158]\n [-0.97254293 -0.68981333]]\n\n [[-0.18304476 -0.8371425 ]\n [ 2.18985366 -0.9740637 ]]]" }, { "code": null, "e": 26940, "s": 26887, "text": "Code 4 : Manipulations with randomly created array " }, { "code": null, "e": 26948, "s": 26940, "text": "Python3" }, { "code": "# Python Program illustrating# numpy.random.randn() method import numpy as geek # 3D Array array = geek.random.randn(2, 2 ,2)print(\"3D Array filled with random values : \\n\", array); # Multiplying values with 3print(\"\\nArray * 3 : \\n\", array *3) # Or we cab directly do so byarray = geek.random.randn(2, 2 ,2) * 3 + 2print(\"\\nArray * 3 + 2 : \\n\", array);", "e": 27312, "s": 26948, "text": null }, { "code": null, "e": 27323, "s": 27312, "text": "Output : " }, { "code": null, "e": 27744, "s": 27323, "text": "3D Array filled with random values : \n [[[ 1.9609643 -1.89882763]\n [ 0.52252173 0.08159455]]\n\n [[-0.6060213 -0.86759247]\n [ 0.53870235 -0.77388125]]]\n\nArray * 3 : \n [[[ 5.88289289 -5.69648288]\n [ 1.56756519 0.24478366]]\n\n [[-1.81806391 -2.6027774 ]\n [ 1.61610704 -2.32164376]]]\n\nArray * 3 + 2 : \n [[[-2.73766306 6.80761741]\n [-1.57909191 -1.64195796]]\n\n [[ 0.51019498 1.30017345]\n [ 3.8107863 -4.07438963]]]" }, { "code": null, "e": 28366, "s": 27744, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.randn.htmlNote : These codes won’t run on online IDE’s. Please run them on your systems to explore the working. . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28380, "s": 28366, "text": "sumitgumber28" }, { "code": null, "e": 28395, "s": 28380, "text": "kothavvsaakash" }, { "code": null, "e": 28424, "s": 28395, "text": "Python numpy-Random sampling" }, { "code": null, "e": 28437, "s": 28424, "text": "Python-numpy" }, { "code": null, "e": 28444, "s": 28437, "text": "Python" }, { "code": null, "e": 28542, "s": 28444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28560, "s": 28542, "text": "Python Dictionary" }, { "code": null, "e": 28595, "s": 28560, "text": "Read a file line by line in Python" }, { "code": null, "e": 28617, "s": 28595, "text": "Enumerate() in Python" }, { "code": null, "e": 28649, "s": 28617, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28679, "s": 28649, "text": "Iterate over a list in Python" }, { "code": null, "e": 28721, "s": 28679, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28747, "s": 28721, "text": "Python String | replace()" }, { "code": null, "e": 28784, "s": 28747, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28827, "s": 28784, "text": "Python program to convert a list to string" } ]
All about Functions and Scopes in JavaScript - GeeksforGeeks
19 Sep, 2021 In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to – understand different types of functions declaration. make better use of functions. understand how different scopes and scope chain works in JS. learn about closures and how to use them. We will understand all these concepts through the examples & also understand their implementations. Let’s begin the discussion with Javascript Function. Functions: Function allows us to declare & pack a bunch of code in a block so that we can use (and reuse) a block of code in our programs. Sometimes, they take some values as `parameters` to do the operation and return some value as a result of the operation. Example: Javascript function add(a, b) { // a and b are the parameters of this // function code to do the operation return a + b; // return statement} // Invoking the function and 2, 3// are arguments hereadd(2, 3); Output: 5 First-Class Citizen: If any programming language has the ability to treat functions as values, to pass them as arguments and to return a function from another function then it is said that programming language has First Class Functions and the functions are called First-Class Citizens in that programming language. Functions will be considered as First-Class Citizen in JavaScript if the functions: store functions in a variable. pass a function as an argument to another function. return a function from another function. Function Expressions: When a function is stored inside a variable, it is called a function expression. This can be named or anonymous. If a function doesn’t have any name and is stored in a variable, then it would be known as an anonymous function expression. Otherwise, it would be known as a named function expression. Please refer to the JavaScript Function expression article for more details. Example: Javascript // Anonymous function expressionconst add = function (a, b){ return a + b;} // Named function expressionconst subtractResult = function subtract(a, b){ return a - b;} console.log(add(3, 2)); // 5console.log(subtractResult(3, 2)); // 1 The output will be 5 & 1 respectively. Callbacks: Storing a function in a variable makes it really easy to pass a function to another function as an argument. A function that takes other functions as arguments or returns a function is known as a higher-order function. A function that is passed as an argument into another function is known as a callback function. In simple words, If we want to execute a function right after the return of some other function, then callbacks can be used. Please refer to theavaScript | Callbacks article for more details. Example: Javascript function showLength(name, callback) { callback(name);} // function expression `nameLength`const nameLength = function (name) { console.log(`Given Name ${name} which is ${name.length} chars long`);}; // Passing `nameLength` as a callback functionshowLength("GeeksforGeek", nameLength); Output: Given Name GeeksforGeek which is 12 characters long Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character that allows declaring the embedded expressions. Generally, we use callback function in array methods – forEach(), map(), filter(), reduce(). Scope: It is a region of the program where a variable can be accessed. In other words, scope determines the accessibility/visibility of a variable. Since JavaScript looks like a C-family language, it is very obvious to think that scoping in JavaScript is similar to that in most of the back-end programming languages like C, C++ or Java. Please refer to the What is Variable Scope in JavaScript? article for more details. There’re 3 kinds of scopes in JavaScript: Global scope: Variables declared outside of all functions are known as global variables and in the global scope. Global variables are accessible anywhere in the program. Function scope: Variables that are declared inside a function are called local variables and in the function scope. Local variables are accessible anywhere inside the function. Block scope: Variable that is declared inside a specific block & can’t be accessed outside of that block. In order to access the variables of that specific block, we need to create object for it. The code inside a function has access to: the function’s arguments. local variables declared inside the function. variables declared in its parent function’s scope. global variables. Javascript const name = "GeeksforGeeks"; function introduceMyself(greet) { const audience = "Everyone"; function introduce() { console.log(`${greet} ${audience}, This is ${name} Learning!`); } introduce();} introduceMyself("Hello"); Output: Hello Everyone, This is GeeksforGeeks Learning! Block scope: This tells us that any variable declared inside a block ({}) can be accessed only inside that block. Now, what is a block? a block {} is used to group JavaScript statements together into 1 group so that it can be used anywhere in the program where only 1 statement is expected to be written. Block scope is related to variables declared with `let` and `const` only. Variables declared with `var` do not have block scope. Example: { let a = 3; var b = 2; } console.log(a); //Uncaught ReferenceError: a is not defined console.log(b); // 2 as variables declared with `var` is functionally and globally scoped NOT block scoped Scope chain: Whenever our code tries to access a variable during the function call, it starts the searching from local variables. And if the variable is not found, it’ll continue searching in its outer scope or parent functions’ scope until it reaches the global scope and completes searching for the variable there. Searching for any variable happens along the scope chain or in different scopes until we get the variable. If the variable is not found in the global scope as well, a reference error is thrown. Example: Javascript const name = "GeeksforGeeks"; function introduceMyself(greet) { const audience = "Everyone"; function introduce() { console.log(`${greet} ${audience}, This is ${name} Learning`); } introduce();} introduceMyself("Hello"); Output: Hello Everyone, This is GeeksforGeeks Learning In the above example, when the code attempts to access variable `name` inside the `introduce()` function, it didn’t get the variable there and tried to search in its parent function’s (`introduceMyself()`) scope. And as it was not there, it finally went up to global scope to access the variable and got the value of the variable `name`. Variable shadowing: If we declare a variable with the same name as another variable in the scope chain, the variable with local scope will shadow the variable at the outer scope. This is known as variable shadowing. Please refer to the Variable Shadowing in JavaScript article for further details. Example 1: Javascript let name = "Abhijit";var sector = "Government"; { let name = "Souvik"; // as `var` is NOT block scoped(globally s // coped here), it'll update the value var sector = "Private"; console.log(name); //Souvik console.log(sector); //Private} console.log(name); //Abhijitconsole.log(sector); //Private Output: Souvik Private Abhijit Private Example 2: Javascript let name = "Abhijit";var sector = "Government"; function showDetails() { let name = "Souvik"; // `var` is functionally scoped here, // so it'll create new reference with // the given value for organization var sector = "Private"; console.log(name); // Souvik console.log(sector); // Private} showDetails();console.log(name); // Abhijitconsole.log(sector); // Government Explanation: In the case of example 1, the `name` variable is shadowing the variable with the same name at the outer scope inside the block as we have used `let` to declare the variable. But, the `sector` variable is also updating the value at the same time as we have used `var` to declare it. And as we know `var` is functionally and globally scoped, the declaration with the same name(`sector`) inside the block will update the value at the same reference. Whereas in the case of example 2, the `sector` variable inside the function is function scoped and will create a new reference which will just shadow the variable with the same name declared outside. Output: Souvik Private Abhijit Government Closure: It is an ability of a function to remember the variables and functions that are declared in its outer scope. MDN defines closure as -“The combination of a function bundled together with references to its surrounding state or the lexical environment“ Now, if you’re thinking, what’s the lexical environment? function’s local environment along with its parent function’s environment forms lexical environment. Please refer to the Closure in JavaScript article to understand this concept. Example: Javascript function closureDemo(){ const a = 3; return function (){ console.log(a); }} // Returns the definition of inner functionconst innerFunction = closureDemo();innerFunction(); // 3 The output will be 3. In the above example, when the `closureDemo()` function is called, it’ll return the inner function along with its lexical scope. Then when we attempt to execute the returned function, it’ll try to log the value of `a` and get the value from its lexical scope’s reference. This is called closure. Even after the outer function’s execution, the returned function still holds the reference of the lexical scope. Advantages: Currying Memoization Module design pattern Disadvantages: Overconsumption of memory might lead up to the memory leak as the innermost function holds the reference of the lexical scope and the variables declared in its lexical scope won’t be garbage collected even after the outer function has been executed. Immediately-Invoked Function Expression(IIFE): An immediately-invoked function expression or IIFE is a function that’s called immediately once it’s defined. Please refer to the JavaScript | Immediately Invoked Function Expressions (IIFE) article for further details. Syntax: (function task(){ console.log("Currently writing a blog on JS functions"); })(); We’re basically wrapping a function in parenthesis and then adding a pair of parenthesis at the end to invoke it. Passing arguments into IIFE: We can also pass arguments into IIFE. The second pair of parenthesis not only can be used to invoke the function immediately but also can be used to pass any arguments into the IIFE. (function showName(name){ console.log(`Given name is ${name}`); // Given name is Souvik })("Souvik"); IIFE and private scope: If we can use IIFE along with closure, we can create a private scope and can protect some variables from being accessed externally. The same idea is used in module design patterns to keep variables private. Example: Javascript // Module patternlet greet = (function () { const name = "GeekforGeeks"; // Private variable return { introduce: function () { console.log(`Hello, This is ${name} Learning!`); }, };})(); console.log(greet.name); //undefined // Hello, This is GeekforGeeks Learning!greet.introduce(); IIFE helps to prevent access to the `name` variable here. And the returned object’s `introduce()` method retains the scope of its parent function(due to closure), we got a public interface to interact with `name`. Output: undefined Hello, This is GeekforGeeks Learning! Blogathon-2021 Functions javascript-basics javascript-functions JavaScript-Questions Blogathon JavaScript Web Technologies Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL Query to Create Table With a Primary Key How to Create a Table With Multiple Foreign Keys in SQL? How to pass data into table from a form using React Components Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js
[ { "code": null, "e": 24838, "s": 24810, "text": "\n19 Sep, 2021" }, { "code": null, "e": 24972, "s": 24838, "text": "In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to –" }, { "code": null, "e": 25025, "s": 24972, "text": "understand different types of functions declaration." }, { "code": null, "e": 25055, "s": 25025, "text": "make better use of functions." }, { "code": null, "e": 25116, "s": 25055, "text": "understand how different scopes and scope chain works in JS." }, { "code": null, "e": 25158, "s": 25116, "text": "learn about closures and how to use them." }, { "code": null, "e": 25311, "s": 25158, "text": "We will understand all these concepts through the examples & also understand their implementations. Let’s begin the discussion with Javascript Function." }, { "code": null, "e": 25571, "s": 25311, "text": "Functions: Function allows us to declare & pack a bunch of code in a block so that we can use (and reuse) a block of code in our programs. Sometimes, they take some values as `parameters` to do the operation and return some value as a result of the operation." }, { "code": null, "e": 25582, "s": 25573, "text": "Example:" }, { "code": null, "e": 25593, "s": 25582, "text": "Javascript" }, { "code": "function add(a, b) { // a and b are the parameters of this // function code to do the operation return a + b; // return statement} // Invoking the function and 2, 3// are arguments hereadd(2, 3);", "e": 25802, "s": 25593, "text": null }, { "code": null, "e": 25811, "s": 25802, "text": "Output: " }, { "code": null, "e": 25813, "s": 25811, "text": "5" }, { "code": null, "e": 26213, "s": 25813, "text": "First-Class Citizen: If any programming language has the ability to treat functions as values, to pass them as arguments and to return a function from another function then it is said that programming language has First Class Functions and the functions are called First-Class Citizens in that programming language. Functions will be considered as First-Class Citizen in JavaScript if the functions:" }, { "code": null, "e": 26244, "s": 26213, "text": "store functions in a variable." }, { "code": null, "e": 26296, "s": 26244, "text": "pass a function as an argument to another function." }, { "code": null, "e": 26337, "s": 26296, "text": "return a function from another function." }, { "code": null, "e": 26735, "s": 26337, "text": "Function Expressions: When a function is stored inside a variable, it is called a function expression. This can be named or anonymous. If a function doesn’t have any name and is stored in a variable, then it would be known as an anonymous function expression. Otherwise, it would be known as a named function expression. Please refer to the JavaScript Function expression article for more details." }, { "code": null, "e": 26744, "s": 26735, "text": "Example:" }, { "code": null, "e": 26755, "s": 26744, "text": "Javascript" }, { "code": "// Anonymous function expressionconst add = function (a, b){ return a + b;} // Named function expressionconst subtractResult = function subtract(a, b){ return a - b;} console.log(add(3, 2)); // 5console.log(subtractResult(3, 2)); // 1", "e": 26998, "s": 26755, "text": null }, { "code": null, "e": 27037, "s": 26998, "text": "The output will be 5 & 1 respectively." }, { "code": null, "e": 27555, "s": 27037, "text": "Callbacks: Storing a function in a variable makes it really easy to pass a function to another function as an argument. A function that takes other functions as arguments or returns a function is known as a higher-order function. A function that is passed as an argument into another function is known as a callback function. In simple words, If we want to execute a function right after the return of some other function, then callbacks can be used. Please refer to theavaScript | Callbacks article for more details." }, { "code": null, "e": 27564, "s": 27555, "text": "Example:" }, { "code": null, "e": 27575, "s": 27564, "text": "Javascript" }, { "code": "function showLength(name, callback) { callback(name);} // function expression `nameLength`const nameLength = function (name) { console.log(`Given Name ${name} which is ${name.length} chars long`);}; // Passing `nameLength` as a callback functionshowLength(\"GeeksforGeek\", nameLength); ", "e": 27867, "s": 27575, "text": null }, { "code": null, "e": 27875, "s": 27867, "text": "Output:" }, { "code": null, "e": 27927, "s": 27875, "text": "Given Name GeeksforGeek which is 12 characters long" }, { "code": null, "e": 28326, "s": 27927, "text": "Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character that allows declaring the embedded expressions. Generally, we use callback function in array methods – forEach(), map(), filter(), reduce()." }, { "code": null, "e": 28790, "s": 28326, "text": "Scope: It is a region of the program where a variable can be accessed. In other words, scope determines the accessibility/visibility of a variable. Since JavaScript looks like a C-family language, it is very obvious to think that scoping in JavaScript is similar to that in most of the back-end programming languages like C, C++ or Java. Please refer to the What is Variable Scope in JavaScript? article for more details. There’re 3 kinds of scopes in JavaScript:" }, { "code": null, "e": 28960, "s": 28790, "text": "Global scope: Variables declared outside of all functions are known as global variables and in the global scope. Global variables are accessible anywhere in the program." }, { "code": null, "e": 29139, "s": 28960, "text": "Function scope: Variables that are declared inside a function are called local variables and in the function scope. Local variables are accessible anywhere inside the function. " }, { "code": null, "e": 29335, "s": 29139, "text": "Block scope: Variable that is declared inside a specific block & can’t be accessed outside of that block. In order to access the variables of that specific block, we need to create object for it." }, { "code": null, "e": 29377, "s": 29335, "text": "The code inside a function has access to:" }, { "code": null, "e": 29403, "s": 29377, "text": "the function’s arguments." }, { "code": null, "e": 29449, "s": 29403, "text": "local variables declared inside the function." }, { "code": null, "e": 29500, "s": 29449, "text": "variables declared in its parent function’s scope." }, { "code": null, "e": 29518, "s": 29500, "text": "global variables." }, { "code": null, "e": 29529, "s": 29518, "text": "Javascript" }, { "code": "const name = \"GeeksforGeeks\"; function introduceMyself(greet) { const audience = \"Everyone\"; function introduce() { console.log(`${greet} ${audience}, This is ${name} Learning!`); } introduce();} introduceMyself(\"Hello\");", "e": 29760, "s": 29529, "text": null }, { "code": null, "e": 29768, "s": 29760, "text": "Output:" }, { "code": null, "e": 29816, "s": 29768, "text": "Hello Everyone, This is GeeksforGeeks Learning!" }, { "code": null, "e": 29932, "s": 29816, "text": "Block scope: This tells us that any variable declared inside a block ({}) can be accessed only inside that block. " }, { "code": null, "e": 30123, "s": 29932, "text": "Now, what is a block? a block {} is used to group JavaScript statements together into 1 group so that it can be used anywhere in the program where only 1 statement is expected to be written." }, { "code": null, "e": 30252, "s": 30123, "text": "Block scope is related to variables declared with `let` and `const` only. Variables declared with `var` do not have block scope." }, { "code": null, "e": 30261, "s": 30252, "text": "Example:" }, { "code": null, "e": 30465, "s": 30261, "text": "{\n let a = 3;\n var b = 2;\n}\n\nconsole.log(a); //Uncaught ReferenceError: a is not defined\nconsole.log(b); // 2 as variables declared with `var` is \nfunctionally and globally scoped NOT block scoped" }, { "code": null, "e": 30980, "s": 30467, "text": "Scope chain: Whenever our code tries to access a variable during the function call, it starts the searching from local variables. And if the variable is not found, it’ll continue searching in its outer scope or parent functions’ scope until it reaches the global scope and completes searching for the variable there. Searching for any variable happens along the scope chain or in different scopes until we get the variable. If the variable is not found in the global scope as well, a reference error is thrown. " }, { "code": null, "e": 30989, "s": 30980, "text": "Example:" }, { "code": null, "e": 31000, "s": 30989, "text": "Javascript" }, { "code": "const name = \"GeeksforGeeks\"; function introduceMyself(greet) { const audience = \"Everyone\"; function introduce() { console.log(`${greet} ${audience}, This is ${name} Learning`); } introduce();} introduceMyself(\"Hello\");", "e": 31234, "s": 31000, "text": null }, { "code": null, "e": 31242, "s": 31234, "text": "Output:" }, { "code": null, "e": 31289, "s": 31242, "text": "Hello Everyone, This is GeeksforGeeks Learning" }, { "code": null, "e": 31627, "s": 31289, "text": "In the above example, when the code attempts to access variable `name` inside the `introduce()` function, it didn’t get the variable there and tried to search in its parent function’s (`introduceMyself()`) scope. And as it was not there, it finally went up to global scope to access the variable and got the value of the variable `name`." }, { "code": null, "e": 31925, "s": 31627, "text": "Variable shadowing: If we declare a variable with the same name as another variable in the scope chain, the variable with local scope will shadow the variable at the outer scope. This is known as variable shadowing. Please refer to the Variable Shadowing in JavaScript article for further details." }, { "code": null, "e": 31936, "s": 31925, "text": "Example 1:" }, { "code": null, "e": 31947, "s": 31936, "text": "Javascript" }, { "code": "let name = \"Abhijit\";var sector = \"Government\"; { let name = \"Souvik\"; // as `var` is NOT block scoped(globally s // coped here), it'll update the value var sector = \"Private\"; console.log(name); //Souvik console.log(sector); //Private} console.log(name); //Abhijitconsole.log(sector); //Private", "e": 32256, "s": 31947, "text": null }, { "code": null, "e": 32264, "s": 32256, "text": "Output:" }, { "code": null, "e": 32295, "s": 32264, "text": "Souvik\nPrivate\nAbhijit\nPrivate" }, { "code": null, "e": 32306, "s": 32295, "text": "Example 2:" }, { "code": null, "e": 32317, "s": 32306, "text": "Javascript" }, { "code": "let name = \"Abhijit\";var sector = \"Government\"; function showDetails() { let name = \"Souvik\"; // `var` is functionally scoped here, // so it'll create new reference with // the given value for organization var sector = \"Private\"; console.log(name); // Souvik console.log(sector); // Private} showDetails();console.log(name); // Abhijitconsole.log(sector); // Government", "e": 32699, "s": 32317, "text": null }, { "code": null, "e": 33359, "s": 32699, "text": "Explanation: In the case of example 1, the `name` variable is shadowing the variable with the same name at the outer scope inside the block as we have used `let` to declare the variable. But, the `sector` variable is also updating the value at the same time as we have used `var` to declare it. And as we know `var` is functionally and globally scoped, the declaration with the same name(`sector`) inside the block will update the value at the same reference. Whereas in the case of example 2, the `sector` variable inside the function is function scoped and will create a new reference which will just shadow the variable with the same name declared outside." }, { "code": null, "e": 33367, "s": 33359, "text": "Output:" }, { "code": null, "e": 33401, "s": 33367, "text": "Souvik\nPrivate\nAbhijit\nGovernment" }, { "code": null, "e": 33519, "s": 33401, "text": "Closure: It is an ability of a function to remember the variables and functions that are declared in its outer scope." }, { "code": null, "e": 33660, "s": 33519, "text": "MDN defines closure as -“The combination of a function bundled together with references to its surrounding state or the lexical environment“" }, { "code": null, "e": 33896, "s": 33660, "text": "Now, if you’re thinking, what’s the lexical environment? function’s local environment along with its parent function’s environment forms lexical environment. Please refer to the Closure in JavaScript article to understand this concept." }, { "code": null, "e": 33905, "s": 33896, "text": "Example:" }, { "code": null, "e": 33916, "s": 33905, "text": "Javascript" }, { "code": "function closureDemo(){ const a = 3; return function (){ console.log(a); }} // Returns the definition of inner functionconst innerFunction = closureDemo();innerFunction(); // 3", "e": 34121, "s": 33916, "text": null }, { "code": null, "e": 34143, "s": 34121, "text": "The output will be 3." }, { "code": null, "e": 34552, "s": 34143, "text": "In the above example, when the `closureDemo()` function is called, it’ll return the inner function along with its lexical scope. Then when we attempt to execute the returned function, it’ll try to log the value of `a` and get the value from its lexical scope’s reference. This is called closure. Even after the outer function’s execution, the returned function still holds the reference of the lexical scope." }, { "code": null, "e": 34564, "s": 34552, "text": "Advantages:" }, { "code": null, "e": 34573, "s": 34564, "text": "Currying" }, { "code": null, "e": 34585, "s": 34573, "text": "Memoization" }, { "code": null, "e": 34607, "s": 34585, "text": "Module design pattern" }, { "code": null, "e": 34622, "s": 34607, "text": "Disadvantages:" }, { "code": null, "e": 34872, "s": 34622, "text": "Overconsumption of memory might lead up to the memory leak as the innermost function holds the reference of the lexical scope and the variables declared in its lexical scope won’t be garbage collected even after the outer function has been executed." }, { "code": null, "e": 35139, "s": 34872, "text": "Immediately-Invoked Function Expression(IIFE): An immediately-invoked function expression or IIFE is a function that’s called immediately once it’s defined. Please refer to the JavaScript | Immediately Invoked Function Expressions (IIFE) article for further details." }, { "code": null, "e": 35147, "s": 35139, "text": "Syntax:" }, { "code": null, "e": 35232, "s": 35147, "text": "(function task(){\n console.log(\"Currently writing a blog on JS functions\");\n})();" }, { "code": null, "e": 35346, "s": 35232, "text": "We’re basically wrapping a function in parenthesis and then adding a pair of parenthesis at the end to invoke it." }, { "code": null, "e": 35559, "s": 35346, "text": "Passing arguments into IIFE: We can also pass arguments into IIFE. The second pair of parenthesis not only can be used to invoke the function immediately but also can be used to pass any arguments into the IIFE. " }, { "code": null, "e": 35664, "s": 35559, "text": "(function showName(name){\n console.log(`Given name is ${name}`); // Given name is Souvik\n})(\"Souvik\");" }, { "code": null, "e": 35897, "s": 35664, "text": "IIFE and private scope: If we can use IIFE along with closure, we can create a private scope and can protect some variables from being accessed externally. The same idea is used in module design patterns to keep variables private. " }, { "code": null, "e": 35906, "s": 35897, "text": "Example:" }, { "code": null, "e": 35917, "s": 35906, "text": "Javascript" }, { "code": "// Module patternlet greet = (function () { const name = \"GeekforGeeks\"; // Private variable return { introduce: function () { console.log(`Hello, This is ${name} Learning!`); }, };})(); console.log(greet.name); //undefined // Hello, This is GeekforGeeks Learning!greet.introduce();", "e": 36218, "s": 35917, "text": null }, { "code": null, "e": 36432, "s": 36218, "text": "IIFE helps to prevent access to the `name` variable here. And the returned object’s `introduce()` method retains the scope of its parent function(due to closure), we got a public interface to interact with `name`." }, { "code": null, "e": 36440, "s": 36432, "text": "Output:" }, { "code": null, "e": 36488, "s": 36440, "text": "undefined\nHello, This is GeekforGeeks Learning!" }, { "code": null, "e": 36503, "s": 36488, "text": "Blogathon-2021" }, { "code": null, "e": 36513, "s": 36503, "text": "Functions" }, { "code": null, "e": 36531, "s": 36513, "text": "javascript-basics" }, { "code": null, "e": 36552, "s": 36531, "text": "javascript-functions" }, { "code": null, "e": 36573, "s": 36552, "text": "JavaScript-Questions" }, { "code": null, "e": 36583, "s": 36573, "text": "Blogathon" }, { "code": null, "e": 36594, "s": 36583, "text": "JavaScript" }, { "code": null, "e": 36611, "s": 36594, "text": "Web Technologies" }, { "code": null, "e": 36621, "s": 36611, "text": "Functions" }, { "code": null, "e": 36719, "s": 36621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36728, "s": 36719, "text": "Comments" }, { "code": null, "e": 36741, "s": 36728, "text": "Old Comments" }, { "code": null, "e": 36782, "s": 36741, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 36817, "s": 36782, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 36862, "s": 36817, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 36919, "s": 36862, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 36982, "s": 36919, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 37027, "s": 36982, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37096, "s": 37027, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 37157, "s": 37096, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37229, "s": 37157, "text": "Differences between Functional Components and Class Components in React" } ]
Apache Kafka - Integration With Storm
In this chapter, we will learn how to integrate Kafka with Apache Storm. Storm was originally created by Nathan Marz and team at BackType. In a short time, Apache Storm became a standard for distributed real-time processing system that allows you to process a huge volume of data. Storm is very fast and a benchmark clocked it at over a million tuples processed per second per node. Apache Storm runs continuously, consuming data from the configured sources (Spouts) and passes the data down the processing pipeline (Bolts). Com-bined, Spouts and Bolts make a Topology. Kafka and Storm naturally complement each other, and their powerful cooperation enables real-time streaming analytics for fast-moving big data. Kafka and Storm integration is to make easier for developers to ingest and publish data streams from Storm topologies. A spout is a source of streams. For example, a spout may read tuples off a Kafka Topic and emit them as a stream. A bolt consumes input streams, process and possibly emits new streams. Bolts can do anything from running functions, filtering tuples, do streaming aggregations, streaming joins, talk to databases, and more. Each node in a Storm topology executes in parallel. A topology runs indefinitely until you terminate it. Storm will automatically reassign any failed tasks. Additionally, Storm guarantees that there will be no data loss, even if the machines go down and messages are dropped. Let us go through the Kafka-Storm integration API’s in detail. There are three main classes to integrate Kafka with Storm. They are as follows − BrokerHosts is an interface and ZkHosts and StaticHosts are its two main implementations. ZkHosts is used to track the Kafka brokers dynamically by maintaining the details in ZooKeeper, while StaticHosts is used to manually / statically set the Kafka brokers and its details. ZkHosts is the simple and fast way to access the Kafka broker. The signature of ZkHosts is as follows − public ZkHosts(String brokerZkStr, String brokerZkPath) public ZkHosts(String brokerZkStr) Where brokerZkStr is ZooKeeper host and brokerZkPath is the ZooKeeper path to maintain the Kafka broker details. This API is used to define configuration settings for the Kafka cluster. The signature of Kafka Con-fig is defined as follows public KafkaConfig(BrokerHosts hosts, string topic) Hosts − The BrokerHosts can be ZkHosts / StaticHosts. Topic − topic name. Spoutconfig is an extension of KafkaConfig that supports additional ZooKeeper information. public SpoutConfig(BrokerHosts hosts, string topic, string zkRoot, string id) Hosts − The BrokerHosts can be any implementation of BrokerHosts interface Hosts − The BrokerHosts can be any implementation of BrokerHosts interface Topic − topic name. Topic − topic name. zkRoot − ZooKeeper root path. zkRoot − ZooKeeper root path. id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout. id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout. SchemeAsMultiScheme is an interface that dictates how the ByteBuffer consumed from Kafka gets transformed into a storm tuple. It is derived from MultiScheme and accept implementation of Scheme class. There are lot of implementation of Scheme class and one such implementation is StringScheme, which parses the byte as a simple string. It also controls the naming of your output field. The signature is defined as follows. public SchemeAsMultiScheme(Scheme scheme) Scheme − byte buffer consumed from kafka. Scheme − byte buffer consumed from kafka. KafkaSpout is our spout implementation, which will integrate with Storm. It fetches the mes-sages from kafka topic and emits it into Storm ecosystem as tuples. KafkaSpout get its config-uration details from SpoutConfig. Below is a sample code to create a simple Kafka spout. // ZooKeeper connection string BrokerHosts hosts = new ZkHosts(zkConnString); //Creating SpoutConfig Object SpoutConfig spoutConfig = new SpoutConfig(hosts, topicName, "/" + topicName UUID.randomUUID().toString()); //convert the ByteBuffer to String. spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); //Assign SpoutConfig to KafkaSpout. KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig); Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes WordSplitter-Bolt and WordCounterBolt are used to perform the operations. IRichBolt interface has the following methods − Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout. Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout. Execute − Process a single tuple of input. Execute − Process a single tuple of input. Cleanup − Called when a bolt is going to shut down. Cleanup − Called when a bolt is going to shut down. declareOutputFields − Declares the output schema of the tuple. declareOutputFields − Declares the output schema of the tuple. Let us create SplitBolt.java, which implements the logic to split a sentence into words and CountBolt.java, which implements logic to separate unique words and count its occurrence. import java.util.Map; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.task.OutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.IRichBolt; import backtype.storm.task.TopologyContext; public class SplitBolt implements IRichBolt { private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { String sentence = input.getString(0); String[] words = sentence.split(" "); for(String word: words) { word = word.trim(); if(!word.isEmpty()) { word = word.toLowerCase(); collector.emit(new Values(word)); } } collector.ack(input); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("word")); } @Override public void cleanup() {} @Override public Map<String, Object> getComponentConfiguration() { return null; } } import java.util.Map; import java.util.HashMap; import backtype.storm.tuple.Tuple; import backtype.storm.task.OutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.IRichBolt; import backtype.storm.task.TopologyContext; public class CountBolt implements IRichBolt{ Map<String, Integer> counters; private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.counters = new HashMap<String, Integer>(); this.collector = collector; } @Override public void execute(Tuple input) { String str = input.getString(0); if(!counters.containsKey(str)){ counters.put(str, 1); }else { Integer c = counters.get(str) +1; counters.put(str, c); } collector.ack(input); } @Override public void cleanup() { for(Map.Entry<String, Integer> entry:counters.entrySet()){ System.out.println(entry.getKey()+" : " + entry.getValue()); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public Map<String, Object> getComponentConfiguration() { return null; } } The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create to-pology. shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts. Local Cluster − For development purposes, we can create a local cluster using LocalCluster object and then submit the topology using submitTopology method of LocalCluster class. import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.topology.TopologyBuilder; import java.util.ArrayList; import java.util.List; import java.util.UUID; import backtype.storm.spout.SchemeAsMultiScheme; import storm.kafka.trident.GlobalPartitionInformation; import storm.kafka.ZkHosts; import storm.kafka.Broker; import storm.kafka.StaticHosts; import storm.kafka.BrokerHosts; import storm.kafka.SpoutConfig; import storm.kafka.KafkaConfig; import storm.kafka.KafkaSpout; import storm.kafka.StringScheme; public class KafkaStormSample { public static void main(String[] args) throws Exception{ Config config = new Config(); config.setDebug(true); config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1); String zkConnString = "localhost:2181"; String topic = "my-first-topic"; BrokerHosts hosts = new ZkHosts(zkConnString); SpoutConfig kafkaSpoutConfig = new SpoutConfig (hosts, topic, "/" + topic, UUID.randomUUID().toString()); kafkaSpoutConfig.bufferSizeBytes = 1024 * 1024 * 4; kafkaSpoutConfig.fetchSizeBytes = 1024 * 1024 * 4; kafkaSpoutConfig.forceFromStart = true; kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("kafka-spout", new KafkaSpout(kafkaSpoutCon-fig)); builder.setBolt("word-spitter", new SplitBolt()).shuffleGroup-ing("kafka-spout"); builder.setBolt("word-counter", new CountBolt()).shuffleGroup-ing("word-spitter"); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("KafkaStormSample", config, builder.create-Topology()); Thread.sleep(10000); cluster.shutdown(); } } Before moving compilation, Kakfa-Storm integration needs curator ZooKeeper client java library. Curator version 2.9.1 support Apache Storm version 0.9.5 (which we use in this tutorial). Down-load the below specified jar files and place it in java class path. curator-client-2.9.1.jar curator-framework-2.9.1.jar After including dependency files, compile the program using the following command, javac -cp "/path/to/Kafka/apache-storm-0.9.5/lib/*" *.java Start Kafka Producer CLI (explained in previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below − hello kafka storm spark test message another test message Now execute the application using the following command − java -cp “/path/to/Kafka/apache-storm-0.9.5/lib/*”:. KafkaStormSample The sample output of this application is specified below − storm : 1 test : 2 spark : 1 another : 1 kafka : 1 hello : 1 message : 2 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2040, "s": 1967, "text": "In this chapter, we will learn how to integrate Kafka with Apache Storm." }, { "code": null, "e": 2537, "s": 2040, "text": "Storm was originally created by Nathan Marz and team at BackType. In a short time, Apache Storm became a standard for distributed real-time processing system that allows you to process a huge volume of data. Storm is very fast and a benchmark clocked it at over a million tuples processed per second per node. Apache Storm runs continuously, consuming data from the configured sources (Spouts) and passes the data down the processing pipeline (Bolts). Com-bined, Spouts and Bolts make a Topology." }, { "code": null, "e": 2800, "s": 2537, "text": "Kafka and Storm naturally complement each other, and their powerful cooperation enables real-time streaming analytics for fast-moving big data. Kafka and Storm integration is to make easier for developers to ingest and publish data streams from Storm topologies." }, { "code": null, "e": 3398, "s": 2800, "text": "A spout is a source of streams. For example, a spout may read tuples off a Kafka Topic and emit them as a stream. A bolt consumes input streams, process and possibly emits new streams. Bolts can do anything from running functions, filtering tuples, do streaming aggregations, streaming joins, talk to databases, and more. Each node in a Storm topology executes in parallel. A topology runs indefinitely until you terminate it. Storm will automatically reassign any failed tasks. Additionally, Storm guarantees that there will be no data loss, even if the machines go down and messages are dropped." }, { "code": null, "e": 3543, "s": 3398, "text": "Let us go through the Kafka-Storm integration API’s in detail. There are three main classes to integrate Kafka with Storm. They are as follows −" }, { "code": null, "e": 3882, "s": 3543, "text": "BrokerHosts is an interface and ZkHosts and StaticHosts are its two main implementations. ZkHosts is used to track the Kafka brokers dynamically by maintaining the details in ZooKeeper, while StaticHosts is used to manually / statically set the Kafka brokers and its details. ZkHosts is the simple and fast way to access the Kafka broker." }, { "code": null, "e": 3923, "s": 3882, "text": "The signature of ZkHosts is as follows −" }, { "code": null, "e": 4015, "s": 3923, "text": "public ZkHosts(String brokerZkStr, String brokerZkPath)\npublic ZkHosts(String brokerZkStr)\n" }, { "code": null, "e": 4128, "s": 4015, "text": "Where brokerZkStr is ZooKeeper host and brokerZkPath is the ZooKeeper path to maintain the Kafka broker details." }, { "code": null, "e": 4254, "s": 4128, "text": "This API is used to define configuration settings for the Kafka cluster. The signature of Kafka Con-fig is defined as follows" }, { "code": null, "e": 4307, "s": 4254, "text": "public KafkaConfig(BrokerHosts hosts, string topic)\n" }, { "code": null, "e": 4361, "s": 4307, "text": "Hosts − The BrokerHosts can be ZkHosts / StaticHosts." }, { "code": null, "e": 4381, "s": 4361, "text": "Topic − topic name." }, { "code": null, "e": 4472, "s": 4381, "text": "Spoutconfig is an extension of KafkaConfig that supports additional ZooKeeper information." }, { "code": null, "e": 4551, "s": 4472, "text": "public SpoutConfig(BrokerHosts hosts, string topic, string zkRoot, string id)\n" }, { "code": null, "e": 4626, "s": 4551, "text": "Hosts − The BrokerHosts can be any implementation of BrokerHosts interface" }, { "code": null, "e": 4701, "s": 4626, "text": "Hosts − The BrokerHosts can be any implementation of BrokerHosts interface" }, { "code": null, "e": 4721, "s": 4701, "text": "Topic − topic name." }, { "code": null, "e": 4741, "s": 4721, "text": "Topic − topic name." }, { "code": null, "e": 4771, "s": 4741, "text": "zkRoot − ZooKeeper root path." }, { "code": null, "e": 4801, "s": 4771, "text": "zkRoot − ZooKeeper root path." }, { "code": null, "e": 4919, "s": 4801, "text": "id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout." }, { "code": null, "e": 5037, "s": 4919, "text": "id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout." }, { "code": null, "e": 5459, "s": 5037, "text": "SchemeAsMultiScheme is an interface that dictates how the ByteBuffer consumed from Kafka gets transformed into a storm tuple. It is derived from MultiScheme and accept implementation of Scheme class. There are lot of implementation of Scheme class and one such implementation is StringScheme, which parses the byte as a simple string. It also controls the naming of your output field. The signature is defined as follows." }, { "code": null, "e": 5502, "s": 5459, "text": "public SchemeAsMultiScheme(Scheme scheme)\n" }, { "code": null, "e": 5544, "s": 5502, "text": "Scheme − byte buffer consumed from kafka." }, { "code": null, "e": 5586, "s": 5544, "text": "Scheme − byte buffer consumed from kafka." }, { "code": null, "e": 5806, "s": 5586, "text": "KafkaSpout is our spout implementation, which will integrate with Storm. It fetches the mes-sages from kafka topic and emits it into Storm ecosystem as tuples. KafkaSpout get its config-uration details from SpoutConfig." }, { "code": null, "e": 5861, "s": 5806, "text": "Below is a sample code to create a simple Kafka spout." }, { "code": null, "e": 6274, "s": 5861, "text": "// ZooKeeper connection string\nBrokerHosts hosts = new ZkHosts(zkConnString);\n\n//Creating SpoutConfig Object\nSpoutConfig spoutConfig = new SpoutConfig(hosts, \n topicName, \"/\" + topicName UUID.randomUUID().toString());\n\n//convert the ByteBuffer to String.\nspoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());\n\n//Assign SpoutConfig to KafkaSpout.\nKafkaSpout kafkaSpout = new KafkaSpout(spoutConfig);" }, { "code": null, "e": 6528, "s": 6274, "text": "Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes WordSplitter-Bolt and WordCounterBolt are used to perform the operations." }, { "code": null, "e": 6576, "s": 6528, "text": "IRichBolt interface has the following methods −" }, { "code": null, "e": 6696, "s": 6576, "text": "Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout." }, { "code": null, "e": 6816, "s": 6696, "text": "Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout." }, { "code": null, "e": 6859, "s": 6816, "text": "Execute − Process a single tuple of input." }, { "code": null, "e": 6902, "s": 6859, "text": "Execute − Process a single tuple of input." }, { "code": null, "e": 6954, "s": 6902, "text": "Cleanup − Called when a bolt is going to shut down." }, { "code": null, "e": 7006, "s": 6954, "text": "Cleanup − Called when a bolt is going to shut down." }, { "code": null, "e": 7069, "s": 7006, "text": "declareOutputFields − Declares the output schema of the tuple." }, { "code": null, "e": 7132, "s": 7069, "text": "declareOutputFields − Declares the output schema of the tuple." }, { "code": null, "e": 7314, "s": 7132, "text": "Let us create SplitBolt.java, which implements the logic to split a sentence into words and CountBolt.java, which implements logic to separate unique words and count its occurrence." }, { "code": null, "e": 8550, "s": 7314, "text": "import java.util.Map;\n\nimport backtype.storm.tuple.Tuple;\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.task.TopologyContext;\n\npublic class SplitBolt implements IRichBolt {\n private OutputCollector collector;\n \n @Override\n public void prepare(Map stormConf, TopologyContext context,\n OutputCollector collector) {\n this.collector = collector;\n }\n \n @Override\n public void execute(Tuple input) {\n String sentence = input.getString(0);\n String[] words = sentence.split(\" \");\n \n for(String word: words) {\n word = word.trim();\n \n if(!word.isEmpty()) {\n word = word.toLowerCase();\n collector.emit(new Values(word));\n }\n \n }\n\n collector.ack(input);\n }\n \n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"word\"));\n }\n\n @Override\n public void cleanup() {}\n \n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n \n}" }, { "code": null, "e": 9820, "s": 8550, "text": "import java.util.Map;\nimport java.util.HashMap;\n\nimport backtype.storm.tuple.Tuple;\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.task.TopologyContext;\n\npublic class CountBolt implements IRichBolt{\n Map<String, Integer> counters;\n private OutputCollector collector;\n \n @Override\n public void prepare(Map stormConf, TopologyContext context,\n OutputCollector collector) {\n this.counters = new HashMap<String, Integer>();\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple input) {\n String str = input.getString(0);\n \n if(!counters.containsKey(str)){\n counters.put(str, 1);\n }else {\n Integer c = counters.get(str) +1;\n counters.put(str, c);\n }\n \n collector.ack(input);\n }\n\n @Override\n public void cleanup() {\n for(Map.Entry<String, Integer> entry:counters.entrySet()){\n System.out.println(entry.getKey()+\" : \" + entry.getValue());\n }\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n \n }\n\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n}" }, { "code": null, "e": 10203, "s": 9820, "text": "The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create to-pology. shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts." }, { "code": null, "e": 10381, "s": 10203, "text": "Local Cluster − For development purposes, we can create a local cluster using LocalCluster object and then submit the topology using submitTopology method of LocalCluster class." }, { "code": null, "e": 12163, "s": 10381, "text": "import backtype.storm.Config;\nimport backtype.storm.LocalCluster;\nimport backtype.storm.topology.TopologyBuilder;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.UUID;\n\nimport backtype.storm.spout.SchemeAsMultiScheme;\nimport storm.kafka.trident.GlobalPartitionInformation;\nimport storm.kafka.ZkHosts;\nimport storm.kafka.Broker;\nimport storm.kafka.StaticHosts;\nimport storm.kafka.BrokerHosts;\nimport storm.kafka.SpoutConfig;\nimport storm.kafka.KafkaConfig;\nimport storm.kafka.KafkaSpout;\nimport storm.kafka.StringScheme;\n\npublic class KafkaStormSample {\n public static void main(String[] args) throws Exception{\n Config config = new Config();\n config.setDebug(true);\n config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);\n String zkConnString = \"localhost:2181\";\n String topic = \"my-first-topic\";\n BrokerHosts hosts = new ZkHosts(zkConnString);\n \n SpoutConfig kafkaSpoutConfig = new SpoutConfig (hosts, topic, \"/\" + topic, \n UUID.randomUUID().toString());\n kafkaSpoutConfig.bufferSizeBytes = 1024 * 1024 * 4;\n kafkaSpoutConfig.fetchSizeBytes = 1024 * 1024 * 4;\n kafkaSpoutConfig.forceFromStart = true;\n kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());\n\n TopologyBuilder builder = new TopologyBuilder();\n builder.setSpout(\"kafka-spout\", new KafkaSpout(kafkaSpoutCon-fig));\n builder.setBolt(\"word-spitter\", new SplitBolt()).shuffleGroup-ing(\"kafka-spout\");\n builder.setBolt(\"word-counter\", new CountBolt()).shuffleGroup-ing(\"word-spitter\");\n \n LocalCluster cluster = new LocalCluster();\n cluster.submitTopology(\"KafkaStormSample\", config, builder.create-Topology());\n\n Thread.sleep(10000);\n \n cluster.shutdown();\n }\n}" }, { "code": null, "e": 12422, "s": 12163, "text": "Before moving compilation, Kakfa-Storm integration needs curator ZooKeeper client java library. Curator version 2.9.1 support Apache Storm version 0.9.5 (which we use in this tutorial). Down-load the below specified jar files and place it in java class path." }, { "code": null, "e": 12447, "s": 12422, "text": "curator-client-2.9.1.jar" }, { "code": null, "e": 12475, "s": 12447, "text": "curator-framework-2.9.1.jar" }, { "code": null, "e": 12558, "s": 12475, "text": "After including dependency files, compile the program using the following command," }, { "code": null, "e": 12618, "s": 12558, "text": "javac -cp \"/path/to/Kafka/apache-storm-0.9.5/lib/*\" *.java\n" }, { "code": null, "e": 12767, "s": 12618, "text": "Start Kafka Producer CLI (explained in previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below −" }, { "code": null, "e": 12826, "s": 12767, "text": "hello\nkafka\nstorm\nspark\ntest message\nanother test message\n" }, { "code": null, "e": 12884, "s": 12826, "text": "Now execute the application using the following command −" }, { "code": null, "e": 12955, "s": 12884, "text": "java -cp “/path/to/Kafka/apache-storm-0.9.5/lib/*”:. KafkaStormSample\n" }, { "code": null, "e": 13014, "s": 12955, "text": "The sample output of this application is specified below −" }, { "code": null, "e": 13088, "s": 13014, "text": "storm : 1\ntest : 2\nspark : 1\nanother : 1\nkafka : 1\nhello : 1\nmessage : 2\n" }, { "code": null, "e": 13123, "s": 13088, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 13142, "s": 13123, "text": " Arnab Chakraborty" }, { "code": null, "e": 13177, "s": 13142, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13198, "s": 13177, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 13231, "s": 13198, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 13244, "s": 13231, "text": " Nilay Mehta" }, { "code": null, "e": 13279, "s": 13244, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13297, "s": 13279, "text": " Bigdata Engineer" }, { "code": null, "e": 13330, "s": 13297, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 13348, "s": 13330, "text": " Bigdata Engineer" }, { "code": null, "e": 13381, "s": 13348, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 13399, "s": 13381, "text": " Bigdata Engineer" }, { "code": null, "e": 13406, "s": 13399, "text": " Print" }, { "code": null, "e": 13417, "s": 13406, "text": " Add Notes" } ]
C++ Program to Represent Graph Using Incidence Matrix
The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph. In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e. The incidence matrix representation takes O(Vx E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory. The incidence matrix representation takes O(Vx E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory. Input Output Input − The u and v of an edge {u,v} Output − Incidence matrix of the graph G At first, there are edge count ed_cnt is 0 for the incidence matrix. Begin ed_cnt := ed_cnt + 1 inc_matrix[u, ed_cnt] := 1 inc_matrix[v, ed_cnt] := 1 End Live Demo #include<iostream> using namespace std; int inc_arr[20][20]; //initial array to hold incidence matrix int ed_no = 0; void displayMatrix(int v, int e) { int i, j; for(i = 0; i < v; i++) { for(j = 0; j < e; j++) { cout << inc_arr[i][j] << " "; } cout << endl; } } void add_edge(int u, int v) { //function to add edge into the matrix with edge number inc_arr[u][ed_no] = 1; inc_arr[v][ed_no] = 1; ed_no++; //increase the edge number } main(int argc, char* argv[]) { int v = 6; //there are 6 vertices in the graph int e = 9; //there are 9 edges in the graph add_edge(0, 4); add_edge(0, 3); add_edge(1, 2); add_edge(1, 4); add_edge(1, 5); add_edge(2, 3); add_edge(2, 5); add_edge(5, 3); add_edge(5, 4); displayMatrix(v, e); } 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 1 1
[ { "code": null, "e": 1314, "s": 1062, "text": "The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph." }, { "code": null, "e": 1514, "s": 1314, "text": "In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e." }, { "code": null, "e": 1709, "s": 1514, "text": "The incidence matrix representation takes O(Vx E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory." }, { "code": null, "e": 1904, "s": 1709, "text": "The incidence matrix representation takes O(Vx E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory." }, { "code": null, "e": 1910, "s": 1904, "text": "Input" }, { "code": null, "e": 1917, "s": 1910, "text": "Output" }, { "code": null, "e": 1954, "s": 1917, "text": "Input − The u and v of an edge {u,v}" }, { "code": null, "e": 1995, "s": 1954, "text": "Output − Incidence matrix of the graph G" }, { "code": null, "e": 2064, "s": 1995, "text": "At first, there are edge count ed_cnt is 0 for the incidence matrix." }, { "code": null, "e": 2158, "s": 2064, "text": "Begin\n ed_cnt := ed_cnt + 1\n inc_matrix[u, ed_cnt] := 1\n inc_matrix[v, ed_cnt] := 1\nEnd" }, { "code": null, "e": 2169, "s": 2158, "text": " Live Demo" }, { "code": null, "e": 2971, "s": 2169, "text": "#include<iostream>\nusing namespace std;\nint inc_arr[20][20]; //initial array to hold incidence matrix\nint ed_no = 0;\nvoid displayMatrix(int v, int e) {\n int i, j;\n for(i = 0; i < v; i++) {\n for(j = 0; j < e; j++) {\n cout << inc_arr[i][j] << \" \";\n }\n cout << endl;\n }\n}\nvoid add_edge(int u, int v) { //function to add edge into the matrix with edge number\n inc_arr[u][ed_no] = 1;\n inc_arr[v][ed_no] = 1;\n ed_no++; //increase the edge number\n}\nmain(int argc, char* argv[]) {\n int v = 6; //there are 6 vertices in the graph\n int e = 9; //there are 9 edges in the graph\n add_edge(0, 4);\n add_edge(0, 3);\n add_edge(1, 2);\n add_edge(1, 4);\n add_edge(1, 5);\n add_edge(2, 3);\n add_edge(2, 5);\n add_edge(5, 3);\n add_edge(5, 4);\n displayMatrix(v, e);\n}" }, { "code": null, "e": 3079, "s": 2971, "text": "1 1 0 0 0 0 0 0 0\n0 0 1 1 1 0 0 0 0\n0 0 1 0 0 1 1 0 0\n0 1 0 0 0 1 0 1 0\n1 0 0 1 0 0 0 0 1\n0 0 0 0 1 0 1 1 1" } ]
Password Entropy in Cryptography - GeeksforGeeks
16 Feb, 2021 Password Entropy is the measure of password strength or how strong the given password is. It is a measure of effectiveness of a password against guessing or brute-force attacks. It decides whether the entered password is common and easily crack-able or not. It is calculated by knowing character set (lower alphabets, upper alphabets, numbers, symbols, etc.) used and the length of the created password. It is expressed in terms of bits of entropy per character. Calculation of total number of possible passwords : In this, you will see how to calculate the total number of possible passwords which can be created with a given character set with the help of examples. Example-1 : Consider the following password policy of an information system where users are required to create their password with at least 5 characters and at most 7 characters from the character set with lowercase letters a-z, uppercase letters A-Z and digits 0-9. Calculate the total number of possible passwords which can be created from it. Solution – Total characters = 26(a-z) + 26(A-Z) + 10(0-9) = 62 Passwords must be between 5 characters to 7 characters => P = possible passwords. Example-2 : Consider the following password policy of an information system where users are required to create their password with at least 5 characters and at most 7 characters from the character set with lowercase letters a-z, uppercase letters A-Z and digits 0-9. Calculate the total number of possible passwords using at least one digit which can be created from it. Solution – Total characters = 26(a-z) + 26(A-Z) + 10(0-9) = 62 Passwords which can be formed without using any digit = 62 - 10 (0-9) = 52 Passwords must be between 5 characters to 7 characters with atleast one digit => P = possible passwords. Example-3 : Now assume that attacker uses a machine with a test capacity of cracking 2.5 million passwords/second and on an average success is achieved if it can test 75% of the overall number of the password. Then calculate the time required by the attacker to crack the password in example 2. Solution – Time required = Total number of possible passwords * rate * accuracy = days Calculation of password entropy : In this, you will see how to calculate the password entropy. Password Entropy is calculated by the following formula as follows. Password Entropy = (number of characters in character set) * length of the password Example-4 : Calculate the password entropy of geeksfg123 chosen from the character set used in example 1. Solution – Number of characters in character set = 62 Length of password = 10 (geeksfg123) Password Entropy = bits of entropy per character cryptography Technical Scripter 2020 Computer Networks cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Multiple Access Protocols in Computer Network GSM in Wireless Communication Cryptography and its Types Secure Socket Layer (SSL) Stop and Wait ARQ Introduction and IPv4 Datagram Header Routing Information Protocol (RIP) Dynamic Host Configuration Protocol (DHCP)
[ { "code": null, "e": 24510, "s": 24482, "text": "\n16 Feb, 2021" }, { "code": null, "e": 24973, "s": 24510, "text": "Password Entropy is the measure of password strength or how strong the given password is. It is a measure of effectiveness of a password against guessing or brute-force attacks. It decides whether the entered password is common and easily crack-able or not. It is calculated by knowing character set (lower alphabets, upper alphabets, numbers, symbols, etc.) used and the length of the created password. It is expressed in terms of bits of entropy per character." }, { "code": null, "e": 25025, "s": 24973, "text": "Calculation of total number of possible passwords :" }, { "code": null, "e": 25179, "s": 25025, "text": "In this, you will see how to calculate the total number of possible passwords which can be created with a given character set with the help of examples. " }, { "code": null, "e": 25192, "s": 25179, "text": "Example-1 : " }, { "code": null, "e": 25526, "s": 25192, "text": "Consider the following password policy of an information system where users are required to create their password with at least 5 characters and at most 7 characters from the character set with lowercase letters a-z, uppercase letters A-Z and digits 0-9. Calculate the total number of possible passwords which can be created from it." }, { "code": null, "e": 25538, "s": 25526, "text": "Solution – " }, { "code": null, "e": 25672, "s": 25538, "text": "Total characters = 26(a-z) + 26(A-Z) + 10(0-9) = 62\nPasswords must be between 5 characters to 7 characters\n=> P = possible passwords." }, { "code": null, "e": 25685, "s": 25672, "text": "Example-2 : " }, { "code": null, "e": 26044, "s": 25685, "text": "Consider the following password policy of an information system where users are required to create their password with at least 5 characters and at most 7 characters from the character set with lowercase letters a-z, uppercase letters A-Z and digits 0-9. Calculate the total number of possible passwords using at least one digit which can be created from it." }, { "code": null, "e": 26055, "s": 26044, "text": "Solution –" }, { "code": null, "e": 26288, "s": 26055, "text": "Total characters = 26(a-z) + 26(A-Z) + 10(0-9) = 62\nPasswords which can be formed without using any digit = 62 - 10 (0-9) = 52\nPasswords must be between 5 characters to 7 characters with atleast one digit\n=> P =\n possible passwords." }, { "code": null, "e": 26301, "s": 26288, "text": "Example-3 : " }, { "code": null, "e": 26584, "s": 26301, "text": "Now assume that attacker uses a machine with a test capacity of cracking 2.5 million passwords/second and on an average success is achieved if it can test 75% of the overall number of the password. Then calculate the time required by the attacker to crack the password in example 2." }, { "code": null, "e": 26595, "s": 26584, "text": "Solution –" }, { "code": null, "e": 26672, "s": 26595, "text": "Time required = Total number of possible passwords * rate * accuracy\n= days" }, { "code": null, "e": 26706, "s": 26672, "text": "Calculation of password entropy :" }, { "code": null, "e": 26835, "s": 26706, "text": "In this, you will see how to calculate the password entropy. Password Entropy is calculated by the following formula as follows." }, { "code": null, "e": 26919, "s": 26835, "text": "Password Entropy = (number of characters in character set) * length of the password" }, { "code": null, "e": 26932, "s": 26919, "text": "Example-4 : " }, { "code": null, "e": 27026, "s": 26932, "text": "Calculate the password entropy of geeksfg123 chosen from the character set used in example 1." }, { "code": null, "e": 27037, "s": 27026, "text": "Solution –" }, { "code": null, "e": 27167, "s": 27037, "text": "Number of characters in character set = 62\nLength of password = 10 (geeksfg123)\nPassword Entropy = bits of entropy per character" }, { "code": null, "e": 27180, "s": 27167, "text": "cryptography" }, { "code": null, "e": 27204, "s": 27180, "text": "Technical Scripter 2020" }, { "code": null, "e": 27222, "s": 27204, "text": "Computer Networks" }, { "code": null, "e": 27235, "s": 27222, "text": "cryptography" }, { "code": null, "e": 27253, "s": 27235, "text": "Computer Networks" }, { "code": null, "e": 27351, "s": 27253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27386, "s": 27351, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27419, "s": 27386, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27465, "s": 27419, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 27495, "s": 27465, "text": "GSM in Wireless Communication" }, { "code": null, "e": 27522, "s": 27495, "text": "Cryptography and its Types" }, { "code": null, "e": 27548, "s": 27522, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 27566, "s": 27548, "text": "Stop and Wait ARQ" }, { "code": null, "e": 27604, "s": 27566, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 27639, "s": 27604, "text": "Routing Information Protocol (RIP)" } ]
How to use sizeof() operator to find the size of a data type or a variable in C#
The sizeof() datatype returns the size of a data type. Let’s say you need to find the size of int datatype − sizeof(int); For double datatype sizeof(double); Let us see the complete example to find the size of various datatypes − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { Console.WriteLine("The size of int is {0}", sizeof(int)); Console.WriteLine("The size of int is {0}", sizeof(char)); Console.WriteLine("The size of short is {0}", sizeof(short)); Console.WriteLine("The size of long is {0}", sizeof(long)); Console.WriteLine("The size of double is {0}", sizeof(double)); Console.ReadLine(); } } } The size of int is 4 The size of int is 2 The size of short is 2 The size of long is 8 The size of double is 8
[ { "code": null, "e": 1171, "s": 1062, "text": "The sizeof() datatype returns the size of a data type. Let’s say you need to find the size of int datatype −" }, { "code": null, "e": 1184, "s": 1171, "text": "sizeof(int);" }, { "code": null, "e": 1204, "s": 1184, "text": "For double datatype" }, { "code": null, "e": 1220, "s": 1204, "text": "sizeof(double);" }, { "code": null, "e": 1292, "s": 1220, "text": "Let us see the complete example to find the size of various datatypes −" }, { "code": null, "e": 1303, "s": 1292, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1303, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n\n Console.WriteLine(\"The size of int is {0}\", sizeof(int));\n Console.WriteLine(\"The size of int is {0}\", sizeof(char));\n Console.WriteLine(\"The size of short is {0}\", sizeof(short));\n Console.WriteLine(\"The size of long is {0}\", sizeof(long));\n Console.WriteLine(\"The size of double is {0}\", sizeof(double));\n\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1901, "s": 1790, "text": "The size of int is 4\nThe size of int is 2\nThe size of short is 2\nThe size of long is 8\nThe size of double is 8" } ]
zlib.decompress(s) in Python
06 Mar, 2020 With the help of zlib.decompress(s) method, we can decompress the compressed bytes of string into original string by using zlib.decompress(s) method. Syntax : zlib.decompress(string)Return : Return decompressed string. Example #1 :In this example we can see that by using zlib.decompress(s) method, we are able to decompress the compressed string in the byte format of string by using this method. # import zlib and decompressimport zlib s = b'This is GFG author, and final year student.' # using zlib.compress(s) methodt = zlib.compress(s)print("Compressed String")print(t) print("\nDecompressed String")print(zlib.decompress(t)) Output : Compressed Stringb’x\x9c\x0b\xc9\xc8,V\x00′′w7w\x85\xc4\xd2\x92\x8c\xfc”\x1d\x85\xc4\xbc\x14\x85\xb4\xcc\xbc\xc4\x1c\x85\xca\xd4\xc4′′\x85\xe2\x92\xd2\x94\xd4\xbc\x12=\x00A\xc9\x0f\x0b’ Decompressed Stringb’This is GFG author, and final year student.’ Example #2 : # import zlib and decompressimport zlib s = b'GeeksForGeeks@12345678' # using zlib.compress(s) methodt = zlib.compress(s)print("Compressed String")print(t) print("\nDecompressed String")print(zlib.decompress(t)) Output : Compressed Stringb’x\x9csOM\xcd.v\xcb/r\x07\xd1\x0e\x86F\xc6&\xa6f\xe6\x16\x00X\xf6\x06\xea’ Decompressed Stringb’GeeksForGeeks@12345678′ Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2020" }, { "code": null, "e": 178, "s": 28, "text": "With the help of zlib.decompress(s) method, we can decompress the compressed bytes of string into original string by using zlib.decompress(s) method." }, { "code": null, "e": 247, "s": 178, "text": "Syntax : zlib.decompress(string)Return : Return decompressed string." }, { "code": null, "e": 426, "s": 247, "text": "Example #1 :In this example we can see that by using zlib.decompress(s) method, we are able to decompress the compressed string in the byte format of string by using this method." }, { "code": "# import zlib and decompressimport zlib s = b'This is GFG author, and final year student.' # using zlib.compress(s) methodt = zlib.compress(s)print(\"Compressed String\")print(t) print(\"\\nDecompressed String\")print(zlib.decompress(t))", "e": 665, "s": 426, "text": null }, { "code": null, "e": 674, "s": 665, "text": "Output :" }, { "code": null, "e": 860, "s": 674, "text": "Compressed Stringb’x\\x9c\\x0b\\xc9\\xc8,V\\x00′′w7w\\x85\\xc4\\xd2\\x92\\x8c\\xfc”\\x1d\\x85\\xc4\\xbc\\x14\\x85\\xb4\\xcc\\xbc\\xc4\\x1c\\x85\\xca\\xd4\\xc4′′\\x85\\xe2\\x92\\xd2\\x94\\xd4\\xbc\\x12=\\x00A\\xc9\\x0f\\x0b’" }, { "code": null, "e": 926, "s": 860, "text": "Decompressed Stringb’This is GFG author, and final year student.’" }, { "code": null, "e": 939, "s": 926, "text": "Example #2 :" }, { "code": "# import zlib and decompressimport zlib s = b'GeeksForGeeks@12345678' # using zlib.compress(s) methodt = zlib.compress(s)print(\"Compressed String\")print(t) print(\"\\nDecompressed String\")print(zlib.decompress(t))", "e": 1157, "s": 939, "text": null }, { "code": null, "e": 1166, "s": 1157, "text": "Output :" }, { "code": null, "e": 1259, "s": 1166, "text": "Compressed Stringb’x\\x9csOM\\xcd.v\\xcb/r\\x07\\xd1\\x0e\\x86F\\xc6&\\xa6f\\xe6\\x16\\x00X\\xf6\\x06\\xea’" }, { "code": null, "e": 1304, "s": 1259, "text": "Decompressed Stringb’GeeksForGeeks@12345678′" }, { "code": null, "e": 1325, "s": 1304, "text": "Python-Miscellaneous" }, { "code": null, "e": 1332, "s": 1325, "text": "Python" } ]
Apache Solr - On Windows Environment
In this chapter, we will discuss how to set up Solr in Windows environment. To install Solr on your Windows system, you need to follow the steps given below − Visit the homepage of Apache Solr and click the download button. Visit the homepage of Apache Solr and click the download button. Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip. Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip. Move the file from the downloads folder to the required directory and unzip it. Move the file from the downloads folder to the required directory and unzip it. Suppose you downloaded the Solr fie and extracted it in onto the C drive. In such case, you can start Solr as shown in the following screenshot. To verify the installation, use the following URL in your browser. http://localhost:8983/ If the installation process is successful, then you will get to see the dashboard of the Apache Solr user interface as shown below. We can also communicate with Apache Solr using Java libraries; but before accessing Solr using Java API, you need to set the classpath for those libraries. Set the classpath to Solr libraries in the .bashrc file. Open .bashrc in any of the editors as shown below. $ gedit ~/.bashrc Set classpath for Solr libraries (lib folder in HBase) as shown below. export CLASSPATH = $CLASSPATH://home/hadoop/Solr/lib/* This is to prevent the “class not found” exception while accessing the HBase using Java API. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2183, "s": 2024, "text": "In this chapter, we will discuss how to set up Solr in Windows environment. To install Solr on your Windows system, you need to follow the steps given below −" }, { "code": null, "e": 2248, "s": 2183, "text": "Visit the homepage of Apache Solr and click the download button." }, { "code": null, "e": 2313, "s": 2248, "text": "Visit the homepage of Apache Solr and click the download button." }, { "code": null, "e": 2422, "s": 2313, "text": "Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip." }, { "code": null, "e": 2531, "s": 2422, "text": "Select one of the mirrors to get an index of Apache Solr. From there download the file named Solr-6.2.0.zip." }, { "code": null, "e": 2611, "s": 2531, "text": "Move the file from the downloads folder to the required directory and unzip it." }, { "code": null, "e": 2691, "s": 2611, "text": "Move the file from the downloads folder to the required directory and unzip it." }, { "code": null, "e": 2836, "s": 2691, "text": "Suppose you downloaded the Solr fie and extracted it in onto the C drive. In such case, you can start Solr as shown in the following screenshot." }, { "code": null, "e": 2903, "s": 2836, "text": "To verify the installation, use the following URL in your browser." }, { "code": null, "e": 2926, "s": 2903, "text": "http://localhost:8983/" }, { "code": null, "e": 3058, "s": 2926, "text": "If the installation process is successful, then you will get to see the dashboard of the Apache Solr user interface as shown below." }, { "code": null, "e": 3214, "s": 3058, "text": "We can also communicate with Apache Solr using Java libraries; but before accessing Solr using Java API, you need to set the classpath for those libraries." }, { "code": null, "e": 3322, "s": 3214, "text": "Set the classpath to Solr libraries in the .bashrc file. Open .bashrc in any of the editors as shown below." }, { "code": null, "e": 3341, "s": 3322, "text": "$ gedit ~/.bashrc\n" }, { "code": null, "e": 3412, "s": 3341, "text": "Set classpath for Solr libraries (lib folder in HBase) as shown below." }, { "code": null, "e": 3468, "s": 3412, "text": "export CLASSPATH = $CLASSPATH://home/hadoop/Solr/lib/*\n" }, { "code": null, "e": 3561, "s": 3468, "text": "This is to prevent the “class not found” exception while accessing the HBase using Java API." }, { "code": null, "e": 3596, "s": 3561, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3615, "s": 3596, "text": " Arnab Chakraborty" }, { "code": null, "e": 3650, "s": 3615, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3671, "s": 3650, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3704, "s": 3671, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3717, "s": 3704, "text": " Nilay Mehta" }, { "code": null, "e": 3752, "s": 3717, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3770, "s": 3752, "text": " Bigdata Engineer" }, { "code": null, "e": 3803, "s": 3770, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3821, "s": 3803, "text": " Bigdata Engineer" }, { "code": null, "e": 3854, "s": 3821, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 3872, "s": 3854, "text": " Bigdata Engineer" }, { "code": null, "e": 3879, "s": 3872, "text": " Print" }, { "code": null, "e": 3890, "s": 3879, "text": " Add Notes" } ]
Type Casting operators in C++
A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. The most general cast supported by most of the C++ compilers is as follows (type) expression Where type is the desired data type. There are other casting operators supported by C++, they are listed below - ? const_cast<type> (expr) The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed. ? const_cast<type> (expr) The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed. ? dynamic_cast<type> (expr) The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object. ? dynamic_cast<type> (expr) The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object. ? reinterpret_cast<type> (expr) The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa. ? reinterpret_cast<type> (expr) The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa. ? static_cast<type> (expr) The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer. ? static_cast<type> (expr) The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer. All of the above-mentioned casting operators will be used while working with classes and objects. For now, try the following example to understand a simple cast operators available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program. #include <iostream> using namespace std; main() { double a = 21.09399; float b = 10.20; int c ; c = (int) a; cout << "Line 1 - Value of (int)a is :" << c << endl ; c = (int) b; cout << "Line 2 - Value of (int)b is :" << c << endl ; return 0; } Line 1 - Value of (int)a is :21 Line 2 - Value of (int)b is :10
[ { "code": null, "e": 1236, "s": 1062, "text": "A cast is a special operator that forces one data type to be converted into another. As an operator, a\ncast is unary and has the same precedence as any other unary operator." }, { "code": null, "e": 1311, "s": 1236, "text": "The most general cast supported by most of the C++ compilers is as follows" }, { "code": null, "e": 1329, "s": 1311, "text": "(type) expression" }, { "code": null, "e": 1442, "s": 1329, "text": "Where type is the desired data type. There are other casting operators supported by C++, they are\nlisted below -" }, { "code": null, "e": 1775, "s": 1442, "text": "? const_cast<type> (expr) The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed." }, { "code": null, "e": 2108, "s": 1775, "text": "? const_cast<type> (expr) The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. This type of casting manipulates the const attribute of the passed object, either to be set or removed." }, { "code": null, "e": 2453, "s": 2108, "text": "? dynamic_cast<type> (expr) The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object." }, { "code": null, "e": 2798, "s": 2453, "text": "? dynamic_cast<type> (expr) The dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a A* pointer into a B* pointer only if the object being pointed to actually is a B object." }, { "code": null, "e": 2979, "s": 2798, "text": "? reinterpret_cast<type> (expr) The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa." }, { "code": null, "e": 3160, "s": 2979, "text": "? reinterpret_cast<type> (expr) The reinterpret_cast operator changes a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa." }, { "code": null, "e": 3331, "s": 3160, "text": "? static_cast<type> (expr) The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer." }, { "code": null, "e": 3502, "s": 3331, "text": "? static_cast<type> (expr) The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer." }, { "code": null, "e": 3783, "s": 3502, "text": "All of the above-mentioned casting operators will be used while working with classes and objects.\nFor now, try the following example to understand a simple cast operators available in C++. Copy and\npaste the following C++ program in test.cpp file and compile and run this program." }, { "code": null, "e": 4051, "s": 3783, "text": "#include <iostream>\nusing namespace std;\nmain() {\n double a = 21.09399;\n float b = 10.20;\n int c ;\n c = (int) a;\n cout << \"Line 1 - Value of (int)a is :\" << c << endl ;\n c = (int) b;\n cout << \"Line 2 - Value of (int)b is :\" << c << endl ;\n return 0;\n}" }, { "code": null, "e": 4115, "s": 4051, "text": "Line 1 - Value of (int)a is :21\nLine 2 - Value of (int)b is :10" } ]
How does spring boot connect localhost MySQL
For this, use application.properties − spring.datasource.username=yourMySQLUserName spring.datasource.password=yourMySQLPassword spring.datasource.url=jdbc:mysql://localhost:3306/yoruDatabaseName spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver To understand the above syntax, let us create a table − mysql> create table demo71 −> ( −> id int, −> name varchar(20) −> ); Query OK, 0 rows affected (3.81 sec) Insert some records into the table with the help of insert command − mysql> insert into demo71 values(100,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into demo71 values(101,'David'); Query OK, 1 row affected (0.49 sec) mysql> insert into demo71 values(102,'Bob'); Query OK, 1 row affected (0.15 sec) Display records from the table using select statement − mysql> select *from demo71; This will produce the following output − +------+-------+ | id | name | +------+-------+ | 100 | John | | 101 | David | | 102 | Bob | +------+-------+ 3 rows in set (0.00 sec) To verify the above application.properties is working with local MySQL or not, you can write spring boot application to test. Following is the application.properties file. Following is the controller class code. The code is as follows − package com.demo.controller; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/table") public class TableController { @Autowired EntityManager entityManager; @ResponseBody @GetMapping("/demo71") public String getData() { Query sqlQuery= entityManager.createNativeQuery("select name from demo71"); List<String> result= sqlQuery.getResultList(); StringBuilder sb=new StringBuilder(); Iterator itr= result.iterator(); while(itr.hasNext()) { sb.append(itr.next()+" "); } return sb.toString(); } } Following is the main class. The Java code is as follows − package com.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JavaMysqlDemoApplication { public static void main(String[] args) { SpringApplication.run(JavaMysqlDemoApplication.class, args); } } To run the above, go to the main class and right click and select “Run as Java Application”.After successfully executing, you need to hit below url. The url is as follows − http://localhost:8093/table/demo71 This will produce the following output −
[ { "code": null, "e": 1101, "s": 1062, "text": "For this, use application.properties −" }, { "code": null, "e": 1319, "s": 1101, "text": "spring.datasource.username=yourMySQLUserName\nspring.datasource.password=yourMySQLPassword\nspring.datasource.url=jdbc:mysql://localhost:3306/yoruDatabaseName\nspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver" }, { "code": null, "e": 1375, "s": 1319, "text": "To understand the above syntax, let us create a table −" }, { "code": null, "e": 1481, "s": 1375, "text": "mysql> create table demo71\n−> (\n−> id int,\n−> name varchar(20)\n−> );\nQuery OK, 0 rows affected (3.81 sec)" }, { "code": null, "e": 1550, "s": 1481, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 1798, "s": 1550, "text": "mysql> insert into demo71 values(100,'John');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into demo71 values(101,'David');\nQuery OK, 1 row affected (0.49 sec)\n\nmysql> insert into demo71 values(102,'Bob');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1854, "s": 1798, "text": "Display records from the table using select statement −" }, { "code": null, "e": 1882, "s": 1854, "text": "mysql> select *from demo71;" }, { "code": null, "e": 1923, "s": 1882, "text": "This will produce the following output −" }, { "code": null, "e": 2066, "s": 1923, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 100 | John |\n| 101 | David |\n| 102 | Bob |\n+------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2192, "s": 2066, "text": "To verify the above application.properties is working with local MySQL or not, you can write spring boot application to test." }, { "code": null, "e": 2238, "s": 2192, "text": "Following is the application.properties file." }, { "code": null, "e": 2303, "s": 2238, "text": "Following is the controller class code. The code is as follows −" }, { "code": null, "e": 3280, "s": 2303, "text": "package com.demo.controller;\nimport java.util.Iterator;\nimport java.util.List;\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.bind.annotation.RestController;\n@RestController\n@RequestMapping(\"/table\")\npublic class TableController {\n @Autowired\n EntityManager entityManager;\n @ResponseBody\n @GetMapping(\"/demo71\")\n public String getData() {\n Query sqlQuery= entityManager.createNativeQuery(\"select name from demo71\");\n List<String> result= sqlQuery.getResultList();\n StringBuilder sb=new StringBuilder();\n Iterator itr= result.iterator();\n while(itr.hasNext()) {\n sb.append(itr.next()+\" \");\n }\n return sb.toString();\n }\n}" }, { "code": null, "e": 3339, "s": 3280, "text": "Following is the main class. The Java code is as follows −" }, { "code": null, "e": 3658, "s": 3339, "text": "package com.demo;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n@SpringBootApplication\npublic class JavaMysqlDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(JavaMysqlDemoApplication.class, args);\n }\n}" }, { "code": null, "e": 3807, "s": 3658, "text": "To run the above, go to the main class and right click and select “Run as Java Application”.After successfully executing, you need to hit below url." }, { "code": null, "e": 3831, "s": 3807, "text": "The url is as follows −" }, { "code": null, "e": 3866, "s": 3831, "text": "http://localhost:8093/table/demo71" }, { "code": null, "e": 3907, "s": 3866, "text": "This will produce the following output −" } ]
How to get text from Selenium element WebElement object?
We can get text from a webelement with Selenium webdriver. The getText() methods obtains the innerText of an element. It fetches the text of an element which is visible along with its sub elements. It ignores the trailing and leading spaces. First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css and then apply getText() method on it to get the text content of the element. Let us get the text of the element About Careers at Tutorials on the page− import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class GetElementText{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement p=driver.findElement(By.xpath("//h1")); //getText() to obtain text String s= p.getText(); System.out.println("Text content is : " + s); driver.close(); } }
[ { "code": null, "e": 1304, "s": 1062, "text": "We can get text from a webelement with Selenium webdriver. The getText() methods obtains the innerText of an element. It fetches the text of an element which is visible along with its sub elements. It ignores the trailing and leading spaces." }, { "code": null, "e": 1495, "s": 1304, "text": "First of all we need to identify the element with help of any of the locators like id,\nclass, name, xpath or css and then apply getText() method on it to get the text content of the element." }, { "code": null, "e": 1570, "s": 1495, "text": "Let us get the text of the element About Careers at Tutorials on the page−" }, { "code": null, "e": 2356, "s": 1570, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class GetElementText{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement p=driver.findElement(By.xpath(\"//h1\"));\n //getText() to obtain text\n String s= p.getText();\n System.out.println(\"Text content is : \" + s);\n driver.close();\n }\n}" } ]
Run SQL file in MySQL database from terminal?
To run SQL file in database, you need to use below syntax: mysql -u yourUserName -p yourDatabaseName < yourFileName.sql To understand the above syntax, let us open command prompt using windows+R shortcut key. The snapshot is as follows: After pressing OK button, you will get a command prompt. The snapshot is as follows: Now reach the bin directory, the snapshot is as follows: Here is my file ‘mydb.sql’ which is located in bin directory. The snapshot and content of SQL file is as follows: Now you can type the above syntax which I have discussed to run SQL file. The snapshot of command is as follows: Now you can check the table ‘Instructor’ is created in database test or not. Now switch to database test using USE command. The query is as follows: mysql>Use test Now check the table ‘Instructor’ is present in test database. The query is as follows: Yes, we have Instructor table. Now we need to check the record is present or not which is inserted in the table. The query is as follows: mysql> select *from instructor; The following is the output: +----+-------+ | id | Name | +----+-------+ | 1 | John | | 2 | Larry | | 3 | Sam | +----+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1121, "s": 1062, "text": "To run SQL file in database, you need to use below syntax:" }, { "code": null, "e": 1182, "s": 1121, "text": "mysql -u yourUserName -p yourDatabaseName < yourFileName.sql" }, { "code": null, "e": 1271, "s": 1182, "text": "To understand the above syntax, let us open command prompt using windows+R shortcut key." }, { "code": null, "e": 1299, "s": 1271, "text": "The snapshot is as follows:" }, { "code": null, "e": 1384, "s": 1299, "text": "After pressing OK button, you will get a command prompt. The snapshot is as follows:" }, { "code": null, "e": 1441, "s": 1384, "text": "Now reach the bin directory, the snapshot is as follows:" }, { "code": null, "e": 1555, "s": 1441, "text": "Here is my file ‘mydb.sql’ which is located in bin directory. The snapshot and content of SQL file is as follows:" }, { "code": null, "e": 1668, "s": 1555, "text": "Now you can type the above syntax which I have discussed to run SQL file. The snapshot of command is as follows:" }, { "code": null, "e": 1745, "s": 1668, "text": "Now you can check the table ‘Instructor’ is created in database test or not." }, { "code": null, "e": 1817, "s": 1745, "text": "Now switch to database test using USE command. The query is as follows:" }, { "code": null, "e": 1832, "s": 1817, "text": "mysql>Use test" }, { "code": null, "e": 1919, "s": 1832, "text": "Now check the table ‘Instructor’ is present in test database. The query is as follows:" }, { "code": null, "e": 2057, "s": 1919, "text": "Yes, we have Instructor table. Now we need to check the record is present or not which is inserted in the table. The query is as follows:" }, { "code": null, "e": 2089, "s": 2057, "text": "mysql> select *from instructor;" }, { "code": null, "e": 2118, "s": 2089, "text": "The following is the output:" }, { "code": null, "e": 2248, "s": 2118, "text": "+----+-------+\n| id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Larry |\n| 3 | Sam |\n+----+-------+\n3 rows in set (0.00 sec)" } ]
MATLAB - The Nested Loops
MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. The syntax for a nested for loop statement in MATLAB is as follows − for m = 1:j for n = 1:k <statements>; end end The syntax for a nested while loop statement in MATLAB is as follows − while <expression1> while <expression2> <statements> end end Let us use a nested for loop to display all the prime numbers from 1 to 100. Create a script file and type the following code − for i = 2:100 for j = 2:100 if(~mod(i,j)) break; % if factor found, not prime end end if(j > (i/j)) fprintf('%d is prime\n', i); end end When you run the file, it displays the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2256, "s": 2141, "text": "MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate the concept." }, { "code": null, "e": 2325, "s": 2256, "text": "The syntax for a nested for loop statement in MATLAB is as follows −" }, { "code": null, "e": 2384, "s": 2325, "text": "for m = 1:j\n for n = 1:k\n <statements>;\n end\nend\n" }, { "code": null, "e": 2455, "s": 2384, "text": "The syntax for a nested while loop statement in MATLAB is as follows −" }, { "code": null, "e": 2529, "s": 2455, "text": "while <expression1>\n while <expression2>\n <statements>\n end\nend\n" }, { "code": null, "e": 2657, "s": 2529, "text": "Let us use a nested for loop to display all the prime numbers from 1 to 100. Create a script file and type the following code −" }, { "code": null, "e": 2835, "s": 2657, "text": "for i = 2:100\n for j = 2:100\n if(~mod(i,j)) \n break; % if factor found, not prime\n end \n end\n if(j > (i/j))\n fprintf('%d is prime\\n', i);\n end\nend" }, { "code": null, "e": 2893, "s": 2835, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 3190, "s": 2893, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 3223, "s": 3190, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 3236, "s": 3223, "text": " Nouman Azam" }, { "code": null, "e": 3271, "s": 3236, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 3284, "s": 3271, "text": " Nouman Azam" }, { "code": null, "e": 3317, "s": 3284, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 3326, "s": 3317, "text": " Sanjeev" }, { "code": null, "e": 3359, "s": 3326, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 3375, "s": 3359, "text": " TELCOMA Global" }, { "code": null, "e": 3408, "s": 3375, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3424, "s": 3408, "text": " TELCOMA Global" }, { "code": null, "e": 3457, "s": 3424, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 3474, "s": 3457, "text": " Phinite Academy" }, { "code": null, "e": 3481, "s": 3474, "text": " Print" }, { "code": null, "e": 3492, "s": 3481, "text": " Add Notes" } ]
JavaScript filter an array of strings, matching case insensitive substring?
Let’s first create array of strings − let studentDetails = [ {studentName: "John Smith"}, {studentName: "john smith"}, {studentName: "Carol Taylor"} ]; Now, match case insensitive substring, use the filter() and the concept of toLowerCase() in it. Following is the code − let studentDetails = [ {studentName: "John Smith"}, {studentName: "john smith"}, {studentName: "Carol Taylor"} ]; var searchName="John Smith" console.log(studentDetails.filter(obj => obj.studentName.toLowerCase().indexOf(searchName.toLowerCase()) >= 0)); To run the above program, you need to use the following command; node fileName.js. Here, my file name is demo55.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo55.js [ { studentName: 'John Smith' }, { studentName: 'john smith' } ]
[ { "code": null, "e": 1100, "s": 1062, "text": "Let’s first create array of strings −" }, { "code": null, "e": 1223, "s": 1100, "text": "let studentDetails =\n[\n {studentName: \"John Smith\"},\n {studentName: \"john smith\"},\n {studentName: \"Carol Taylor\"}\n];" }, { "code": null, "e": 1343, "s": 1223, "text": "Now, match case insensitive substring, use the filter() and the concept of toLowerCase() in it.\nFollowing is the code −" }, { "code": null, "e": 1607, "s": 1343, "text": "let studentDetails =\n[\n {studentName: \"John Smith\"},\n {studentName: \"john smith\"},\n {studentName: \"Carol Taylor\"}\n];\nvar searchName=\"John Smith\"\nconsole.log(studentDetails.filter(obj =>\nobj.studentName.toLowerCase().indexOf(searchName.toLowerCase()) >= 0));" }, { "code": null, "e": 1672, "s": 1607, "text": "To run the above program, you need to use the following command;" }, { "code": null, "e": 1690, "s": 1672, "text": "node fileName.js." }, { "code": null, "e": 1723, "s": 1690, "text": "Here, my file name is demo55.js." }, { "code": null, "e": 1764, "s": 1723, "text": "This will produce the following output −" }, { "code": null, "e": 1878, "s": 1764, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo55.js\n[ { studentName: 'John Smith' }, { studentName: 'john smith' } ]" } ]
Action Masking with RLlib. RL algorithms learn via trial and... | by Christian Hubbs | Towards Data Science
RL algorithms learn via trial and error. The agent searches the state space early on and takes random actions to learn what leads to a good reward. Pretty straightforward. Unfortunately, this isn’t terribly efficient, especially if we already know something about what makes a good vs. bad action in some states. Thankfully, we can use action masking — a simple technique that sets the probability of bad actions to 0 — to speed learning and improve our policies. We enforce constraints via action masking for a knapsack packing environment and show how to do this using RLlib. Let’s use the classic knapsack problem to develop a concrete example. The knapsack problem (KP) asks you to pack a knapsack to maximize the value in the bag without overloading it. If you have a collection of items like we have shown below, the optimal packing is going to contain three of the yellow boxes and three of the gray boxes for a total of $36 and 15kg (this is the unbounded knapsack problem because you have no limit on how many boxes you can choose). Typically, this problem is solved using dynamic programming or math programming. If we set it up following a math program, we can write out the model as follows: In this case, x_i​ is can be any value ≥0 and symbolizes the number of items i we place into the knapsack. v_i​ and w_i​, are the values and weights of the items respectively. In plain language, this small model is saying we want to maximize the value in the knapsack (which we call z). We do this by finding the largest number of items (x_i) and their values (v_i​) without exceeding the weight limit of the knapsack (W). This formulation is known as an Integer Program (IP) because we have integer decision variables (we can’t pack parts of items, just full, integer values) and is solved using a solver like CPLEX, Gurobi, or GLPK (the last one is free and open source). Enforcing those constraints are built into the model, but it’s not naturally built into RL. The RL model may need to pack the green, 12kg box a few times before learning that it can’t pack that and the yellow, 4kg box, by getting hit with a large, negative reward a few times. The negative reward for over packing is a “soft constraint” because we aren’t explicitly forbidding the algorithm from making these bad decisions. But, if we use action masking, we can ensure that the model doesn’t make dumb choices, which will also help it learn better policies, faster. Let’s put this into action by packing a knapsack using the or-gym library, which contains some classic environments from the operations research field that we can use to train RL agents. If you’re familiar with OpenAI Gym, you’ll use this in the same way. You can install it with pip install or-gym. Once that’s installed, import it and build the Knapsack-v0 environment, which is the unbounded knapsack problem we described above. import or_gymimport numpy as npenv = or_gym.make('Knapsack-v0') The default settings for this environment has 200 different items to choose from and has a maximum weight capacity of 200kg. print("Max weight capacity:\t{}kg".format(env.max_weight))print("Number of items:\t{}".format(env.N))[out]Max weight capacity: 200kgNumber of items: 200 This is fine, but 200 items are a little much to see clearly, so we can pass an env_config dictionary to change some of these parameters to match the example above. Additionally, we can turn action masking on and off by passing mask: True or mask: False to the configuration dictionary. env_config = {'N': 5, 'max_weight': 15, 'item_weights': np.array([1, 12, 2, 1, 4]), 'item_values': np.array([2, 4, 2, 1, 10]), 'mask': True}env = or_gym.make('Knapsack-v0', env_config=env_config)print("Max weight capacity:\t{}kg".format(env.max_weight))print("Number of items:\t{}".format(env.N))[out]Max weight capacity: 15kgNumber of items: 5 Now our environment matches the example above. Let’s look at our state briefly. env.state[out]{'action_mask': array([1, 1, 1, 1, 1]), 'avail_actions': array([1., 1., 1., 1., 1.]), 'state': array([ 1, 12, 2, 1, 4, 2, 4, 2, 1, 10, 0])} When we set the action mask option to True, we get a dictionary output as the state that contains three entries, action_mask, avail_actions, and state. This is the same format for all environments in the or-gym library. The mask is a binary vector where 1 indicates an action is allowed and 0 indicates it is going to break some constraint. In this case, our only constraint is the weight, so if a given item would push the model over weight, it is going to receive a large, negative penalty. The available actions correspond to each of the five items the agent can select for packing. The state is the input that gets passed to the neural network. In this case, we have a vector that has concatenated the item weights and values, and has the current weight tacked on the end (0 when you initialize the environment). If we go ahead and select the 12kg item to pack, we should see that action mask update to eliminate packing any other item that puts the model over the weight limit. state, reward, done, _ = env.step(1)state{'action_mask': array([1, 0, 1, 1, 0]), 'avail_actions': array([1., 1., 1., 1., 1.]), 'state': array([ 1, 12, 2, 1, 4, 2, 4, 2, 1, 10, 12])} If you look at the action_mask, that's exactly what we see. The environment is returning information that we can use to prevent the agent from selecting either the 12kg or the 4kg item because it will violate our constraint. The concept here is really straightforward to apply. After you complete the forward pass through your policy network, you use the mask to update the values for the illegal actions so that they become large, negative numbers. That way, when you pass it through the softmax function, the probabilities associated with these are going to be 0. Now, let’s turn to using RLlib to train a model to respect these constraints. Action masking in RLlib requires building a custom model that handles the logits directly. For a custom environment with action masking, this isn’t as straightforward as I’d like, so I’ll walk you through it step-by-step. There are a lot of pieces we’re going to need to import first. ray and our ray.rllib.agents should be obvious if you're familiar with the library, but we'll also need tune, gym.spaces, ModelCatalog, a Tensorflow or PyTorch model (depending on your preference, for this I'll just stick to TF), and a utility in the or_gym library called create_env that we wrote to make this a bit smoother. import rayfrom ray.rllib import agentsfrom ray import tunefrom ray.rllib.models import ModelCatalogfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2from ray.rllib.models.tf.fcnet import FullyConnectedNetworkfrom ray.rllib.utils import try_import_tffrom gym import spacesfrom or_gym.utils import create_envtf = try_import_tf() We need to tell our neural network explicitly how to handle the different values in our state dictionary. For this, we’ll build a custom model based on the TFModelV2 module from RLlib. This will enable us to build a custom model class and add a forward method to the model in order to use it. Within the forward method, we apply the masks as shown below: class KP0ActionMaskModel(TFModelV2): def __init__(self, obs_space, action_space, num_outputs, model_config, name, true_obs_shape=(11,), action_embed_size=5, *args, **kwargs): super(KP0ActionMaskModel, self).__init__(obs_space, action_space, num_outputs, model_config, name, *args, **kwargs) self.action_embed_model = FullyConnectedNetwork( spaces.Box(0, 1, shape=true_obs_shape), action_space, action_embed_size, model_config, name + "_action_embedding") self.register_variables(self.action_embed_model.variables()) def forward(self, input_dict, state, seq_lens): avail_actions = input_dict["obs"]["avail_actions"] action_mask = input_dict["obs"]["action_mask"] action_embedding, _ = self.action_embed_model({ "obs": input_dict["obs"]["state"]}) intent_vector = tf.expand_dims(action_embedding, 1) action_logits = tf.reduce_sum(avail_actions * intent_vector, axis=1) inf_mask = tf.maximum(tf.log(action_mask), tf.float32.min) return action_logits + inf_mask, state def value_function(self): return self.action_embed_model.value_function() To walk through this, we first initialize the model and pass our true_obs_shape, which is going to match the size of the state. If we stick with our reduced KP, that will be a vector with 11 entries. The other value we need to provide is the action_embed_size, which is going to be the size of our action space (5). From here, the model initializes a FullyConnectedNetwork based on the input values we provided and registers these values. The actual masking takes place in the forward method where we unpack the mask, actions, and state from the observation dictionary provided by our environment. The state yields our action embeddings which gets combined with our mask to provide logits with the smallest value we can provide. This will get passed to a softmax output which will reduce the probability of selecting these actions to 0, effectively blocking the agent from ever taking these illegal actions. Once we have our model in place, we need to register it with the ModelCatalog so RLlib can use it during training. ModelCatalog.register_custom_model('kp_mask', KP0ActionMaskModel) Additionally, we need to register our custom environment to be callable with RLlib. Below, I have a little helper function called register_env which we use to wrap our create_env function and tune's register_env function. Tune needs the base class, not an instance of the environment like we get from or_gym.make(env_name) to work with. So we need to pass this to register_env using a lambda function as shown below. def register_env(env_name, env_config={}): env = create_env(env_name) tune.register_env(env_name, lambda env_name: env(env_name, env_config=env_config)) register_env('Knapsack-v0', env_config=env_config) Finally, we can initialize ray, and pass the model and setup to our trainer. ray.init(ignore_reinit_error=True)trainer_config = { "model": { "custom_model": "kp_mask" }, "env_config": env_config }trainer = agents.ppo.PPOTrainer(env='Knapsack-v0', config=trainer_config) To demonstrate that our constraint works, we can mask a given action by setting one of the values to 0. env = trainer.env_creator('Knapsack-v0')state = env.statestate['action_mask'][0] = 0 We masked action 0, so we shouldn’t see the agent select 0 at all. actions = np.array([trainer.compute_action(state) for i in range(10000)])any(actions==0)[out]False And there we have it! We’ve successfully restricted our output with a custom model in RLlib to enforce constraints. You can use this same setup with tune as well to constrain the action space and provide parametric actions. Masking can work very effectively to free an agent from pernicious local minima. Here, we built a virtual machine assignment environment for or-gym where the model with masking quickly found an excellent policy, while the model without masking got stuck in a local optima. We tried a lot with the reward function first to get it out of that rut, but nothing worked until we applied a mask!
[ { "code": null, "e": 344, "s": 172, "text": "RL algorithms learn via trial and error. The agent searches the state space early on and takes random actions to learn what leads to a good reward. Pretty straightforward." }, { "code": null, "e": 636, "s": 344, "text": "Unfortunately, this isn’t terribly efficient, especially if we already know something about what makes a good vs. bad action in some states. Thankfully, we can use action masking — a simple technique that sets the probability of bad actions to 0 — to speed learning and improve our policies." }, { "code": null, "e": 750, "s": 636, "text": "We enforce constraints via action masking for a knapsack packing environment and show how to do this using RLlib." }, { "code": null, "e": 820, "s": 750, "text": "Let’s use the classic knapsack problem to develop a concrete example." }, { "code": null, "e": 1214, "s": 820, "text": "The knapsack problem (KP) asks you to pack a knapsack to maximize the value in the bag without overloading it. If you have a collection of items like we have shown below, the optimal packing is going to contain three of the yellow boxes and three of the gray boxes for a total of $36 and 15kg (this is the unbounded knapsack problem because you have no limit on how many boxes you can choose)." }, { "code": null, "e": 1376, "s": 1214, "text": "Typically, this problem is solved using dynamic programming or math programming. If we set it up following a math program, we can write out the model as follows:" }, { "code": null, "e": 1552, "s": 1376, "text": "In this case, x_i​ is can be any value ≥0 and symbolizes the number of items i we place into the knapsack. v_i​ and w_i​, are the values and weights of the items respectively." }, { "code": null, "e": 2050, "s": 1552, "text": "In plain language, this small model is saying we want to maximize the value in the knapsack (which we call z). We do this by finding the largest number of items (x_i) and their values (v_i​) without exceeding the weight limit of the knapsack (W). This formulation is known as an Integer Program (IP) because we have integer decision variables (we can’t pack parts of items, just full, integer values) and is solved using a solver like CPLEX, Gurobi, or GLPK (the last one is free and open source)." }, { "code": null, "e": 2616, "s": 2050, "text": "Enforcing those constraints are built into the model, but it’s not naturally built into RL. The RL model may need to pack the green, 12kg box a few times before learning that it can’t pack that and the yellow, 4kg box, by getting hit with a large, negative reward a few times. The negative reward for over packing is a “soft constraint” because we aren’t explicitly forbidding the algorithm from making these bad decisions. But, if we use action masking, we can ensure that the model doesn’t make dumb choices, which will also help it learn better policies, faster." }, { "code": null, "e": 2916, "s": 2616, "text": "Let’s put this into action by packing a knapsack using the or-gym library, which contains some classic environments from the operations research field that we can use to train RL agents. If you’re familiar with OpenAI Gym, you’ll use this in the same way. You can install it with pip install or-gym." }, { "code": null, "e": 3048, "s": 2916, "text": "Once that’s installed, import it and build the Knapsack-v0 environment, which is the unbounded knapsack problem we described above." }, { "code": null, "e": 3112, "s": 3048, "text": "import or_gymimport numpy as npenv = or_gym.make('Knapsack-v0')" }, { "code": null, "e": 3237, "s": 3112, "text": "The default settings for this environment has 200 different items to choose from and has a maximum weight capacity of 200kg." }, { "code": null, "e": 3390, "s": 3237, "text": "print(\"Max weight capacity:\\t{}kg\".format(env.max_weight))print(\"Number of items:\\t{}\".format(env.N))[out]Max weight capacity: 200kgNumber of items: 200" }, { "code": null, "e": 3677, "s": 3390, "text": "This is fine, but 200 items are a little much to see clearly, so we can pass an env_config dictionary to change some of these parameters to match the example above. Additionally, we can turn action masking on and off by passing mask: True or mask: False to the configuration dictionary." }, { "code": null, "e": 4074, "s": 3677, "text": "env_config = {'N': 5, 'max_weight': 15, 'item_weights': np.array([1, 12, 2, 1, 4]), 'item_values': np.array([2, 4, 2, 1, 10]), 'mask': True}env = or_gym.make('Knapsack-v0', env_config=env_config)print(\"Max weight capacity:\\t{}kg\".format(env.max_weight))print(\"Number of items:\\t{}\".format(env.N))[out]Max weight capacity: 15kgNumber of items: 5" }, { "code": null, "e": 4154, "s": 4074, "text": "Now our environment matches the example above. Let’s look at our state briefly." }, { "code": null, "e": 4316, "s": 4154, "text": "env.state[out]{'action_mask': array([1, 1, 1, 1, 1]), 'avail_actions': array([1., 1., 1., 1., 1.]), 'state': array([ 1, 12, 2, 1, 4, 2, 4, 2, 1, 10, 0])}" }, { "code": null, "e": 4809, "s": 4316, "text": "When we set the action mask option to True, we get a dictionary output as the state that contains three entries, action_mask, avail_actions, and state. This is the same format for all environments in the or-gym library. The mask is a binary vector where 1 indicates an action is allowed and 0 indicates it is going to break some constraint. In this case, our only constraint is the weight, so if a given item would push the model over weight, it is going to receive a large, negative penalty." }, { "code": null, "e": 5133, "s": 4809, "text": "The available actions correspond to each of the five items the agent can select for packing. The state is the input that gets passed to the neural network. In this case, we have a vector that has concatenated the item weights and values, and has the current weight tacked on the end (0 when you initialize the environment)." }, { "code": null, "e": 5299, "s": 5133, "text": "If we go ahead and select the 12kg item to pack, we should see that action mask update to eliminate packing any other item that puts the model over the weight limit." }, { "code": null, "e": 5488, "s": 5299, "text": "state, reward, done, _ = env.step(1)state{'action_mask': array([1, 0, 1, 1, 0]), 'avail_actions': array([1., 1., 1., 1., 1.]), 'state': array([ 1, 12, 2, 1, 4, 2, 4, 2, 1, 10, 12])}" }, { "code": null, "e": 5713, "s": 5488, "text": "If you look at the action_mask, that's exactly what we see. The environment is returning information that we can use to prevent the agent from selecting either the 12kg or the 4kg item because it will violate our constraint." }, { "code": null, "e": 6054, "s": 5713, "text": "The concept here is really straightforward to apply. After you complete the forward pass through your policy network, you use the mask to update the values for the illegal actions so that they become large, negative numbers. That way, when you pass it through the softmax function, the probabilities associated with these are going to be 0." }, { "code": null, "e": 6132, "s": 6054, "text": "Now, let’s turn to using RLlib to train a model to respect these constraints." }, { "code": null, "e": 6354, "s": 6132, "text": "Action masking in RLlib requires building a custom model that handles the logits directly. For a custom environment with action masking, this isn’t as straightforward as I’d like, so I’ll walk you through it step-by-step." }, { "code": null, "e": 6744, "s": 6354, "text": "There are a lot of pieces we’re going to need to import first. ray and our ray.rllib.agents should be obvious if you're familiar with the library, but we'll also need tune, gym.spaces, ModelCatalog, a Tensorflow or PyTorch model (depending on your preference, for this I'll just stick to TF), and a utility in the or_gym library called create_env that we wrote to make this a bit smoother." }, { "code": null, "e": 7073, "s": 6744, "text": "import rayfrom ray.rllib import agentsfrom ray import tunefrom ray.rllib.models import ModelCatalogfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2from ray.rllib.models.tf.fcnet import FullyConnectedNetworkfrom ray.rllib.utils import try_import_tffrom gym import spacesfrom or_gym.utils import create_envtf = try_import_tf()" }, { "code": null, "e": 7428, "s": 7073, "text": "We need to tell our neural network explicitly how to handle the different values in our state dictionary. For this, we’ll build a custom model based on the TFModelV2 module from RLlib. This will enable us to build a custom model class and add a forward method to the model in order to use it. Within the forward method, we apply the masks as shown below:" }, { "code": null, "e": 8670, "s": 7428, "text": "class KP0ActionMaskModel(TFModelV2): def __init__(self, obs_space, action_space, num_outputs, model_config, name, true_obs_shape=(11,), action_embed_size=5, *args, **kwargs): super(KP0ActionMaskModel, self).__init__(obs_space, action_space, num_outputs, model_config, name, *args, **kwargs) self.action_embed_model = FullyConnectedNetwork( spaces.Box(0, 1, shape=true_obs_shape), action_space, action_embed_size, model_config, name + \"_action_embedding\") self.register_variables(self.action_embed_model.variables()) def forward(self, input_dict, state, seq_lens): avail_actions = input_dict[\"obs\"][\"avail_actions\"] action_mask = input_dict[\"obs\"][\"action_mask\"] action_embedding, _ = self.action_embed_model({ \"obs\": input_dict[\"obs\"][\"state\"]}) intent_vector = tf.expand_dims(action_embedding, 1) action_logits = tf.reduce_sum(avail_actions * intent_vector, axis=1) inf_mask = tf.maximum(tf.log(action_mask), tf.float32.min) return action_logits + inf_mask, state def value_function(self): return self.action_embed_model.value_function()" }, { "code": null, "e": 9109, "s": 8670, "text": "To walk through this, we first initialize the model and pass our true_obs_shape, which is going to match the size of the state. If we stick with our reduced KP, that will be a vector with 11 entries. The other value we need to provide is the action_embed_size, which is going to be the size of our action space (5). From here, the model initializes a FullyConnectedNetwork based on the input values we provided and registers these values." }, { "code": null, "e": 9578, "s": 9109, "text": "The actual masking takes place in the forward method where we unpack the mask, actions, and state from the observation dictionary provided by our environment. The state yields our action embeddings which gets combined with our mask to provide logits with the smallest value we can provide. This will get passed to a softmax output which will reduce the probability of selecting these actions to 0, effectively blocking the agent from ever taking these illegal actions." }, { "code": null, "e": 9693, "s": 9578, "text": "Once we have our model in place, we need to register it with the ModelCatalog so RLlib can use it during training." }, { "code": null, "e": 9759, "s": 9693, "text": "ModelCatalog.register_custom_model('kp_mask', KP0ActionMaskModel)" }, { "code": null, "e": 10176, "s": 9759, "text": "Additionally, we need to register our custom environment to be callable with RLlib. Below, I have a little helper function called register_env which we use to wrap our create_env function and tune's register_env function. Tune needs the base class, not an instance of the environment like we get from or_gym.make(env_name) to work with. So we need to pass this to register_env using a lambda function as shown below." }, { "code": null, "e": 10389, "s": 10176, "text": "def register_env(env_name, env_config={}): env = create_env(env_name) tune.register_env(env_name, lambda env_name: env(env_name, env_config=env_config)) register_env('Knapsack-v0', env_config=env_config)" }, { "code": null, "e": 10466, "s": 10389, "text": "Finally, we can initialize ray, and pass the model and setup to our trainer." }, { "code": null, "e": 10683, "s": 10466, "text": "ray.init(ignore_reinit_error=True)trainer_config = { \"model\": { \"custom_model\": \"kp_mask\" }, \"env_config\": env_config }trainer = agents.ppo.PPOTrainer(env='Knapsack-v0', config=trainer_config)" }, { "code": null, "e": 10787, "s": 10683, "text": "To demonstrate that our constraint works, we can mask a given action by setting one of the values to 0." }, { "code": null, "e": 10872, "s": 10787, "text": "env = trainer.env_creator('Knapsack-v0')state = env.statestate['action_mask'][0] = 0" }, { "code": null, "e": 10939, "s": 10872, "text": "We masked action 0, so we shouldn’t see the agent select 0 at all." }, { "code": null, "e": 11038, "s": 10939, "text": "actions = np.array([trainer.compute_action(state) for i in range(10000)])any(actions==0)[out]False" }, { "code": null, "e": 11262, "s": 11038, "text": "And there we have it! We’ve successfully restricted our output with a custom model in RLlib to enforce constraints. You can use this same setup with tune as well to constrain the action space and provide parametric actions." } ]
Ruby | Hash Class - GeeksforGeeks
11 Aug, 2021 In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order. The default value of Hashes is nil. When a user tries to access the keys which do not exist in the hash, then the nil value is returned. 1. [] : This method creates a new hash that is populated with the given objects. It is equivalent to creating a hash using literal {Key=>value....}. Keys and values are present in the pair so there is even number of arguments present. Hash[(key=>value)*] Example: Ruby # Ruby program to illustrate# use of []# Using []p Hash["x", 30, "y", 19]p Hash["x" => 30, "y" => 19] Output: {"x"=>30, "y"=>19} {"x"=>30, "y"=>19} 2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value. The values are stored in the hash (if necessary) depends upon the block. Hash.new Hash.new(obj) Hash.new{|hash, key|block} Example: Ruby # Ruby program to illustrate# use of new method # Using new methoda = Hash.new("geeksforgeeks")p a["x"] = 40p a["y"] = 49p a["x"]p a["y"]p a["z"] Output: 40 49 40 49 "geeksforgeeks" 3.try_convert : This method is used to convert obj into hash and returns hash or nil. It return nil when the obj does not convert into hash. Hash.try_convert(obj) Example: Ruby # Ruby program to illustrate# use of try_convert method # Using try_convert methodp Hash.try_convert({3=>8})p Hash.try_convert("3=>8") Output: {3=>8} nil Note: In the below-described methods, hsh variable is the instance of the Hash Class. 1. ==: It is known as Equality. It is used to check if two hashes are equal or not. If they are equal means they contain the same number of keys and the value related to these keys are equal, then it will return true otherwise returns false. hsh1 == hsh2 Example: Ruby # Ruby program to illustrate# use of Equality a1 = {"x" => 4, "y" => 109}a2 = {"x" => 67, "f" => 78, "z" => 21}a3 = {"f" => 78, "x" => 67, "z" => 21} # Using equalityp a1 == a2p a2 == a3 Output: false true 2. [] : It is known as Element Reference. It retrieves the value that stored in the key. If it does not find any value then it return the default value. hsh[key] Example: Ruby # Ruby program to illustrate# use of [] a = {"x" => 45, "y" => 67} # Using []p a["x"]p a["z"] Output: 45 nil 3. []= : It is known as Element Assignment. It associates the value given by value with the key given by key. hsh[key]=value Example: Ruby # Ruby program to illustrate# use of []= a = {"x" => 45, "y" => 67} # Using []=a["x"]= 34a["z"]= 89p a Output: {"x"=>34, "y"=>67, "z"=>89} 4. clear : This method removes all the keys and their values from the hsh. hsh.clear Example: Ruby # Ruby program to illustrate# use of clear method a = {"x" => 45, "y" => 67} # Using clear methodp a.clear Output: {} 5. default : This method return the default value. The value that returned by hsh[key], if key did not exist in hsh. hsh.default(nil=key) Example: Ruby # Ruby program to illustrate# use of default method a = Hash.new("geeksforgeeks") # Using default methodp a.defaultp a.default(2) Output: "geeksforgeeks" "geeksforgeeks" 6. default= : This method sets the default value (the value which is returned for a key and not exists in a hash). hsh.default=obj 7. default_proc : In this method if Hash.new was called with the block. Then it will return block otherwise return nil. hsh.default_proc Example: Ruby # Ruby program to illustrate# use of default_proc method a = Hash.new {|a, v| a[v] = v*v*v} # Using default_proc methodb = a.default_procc = []p b.call(c, 2)p c Output: 8 [nil, nil, 8] 8. delete :This method is used to delete the entry from hash whose key is key by returning the corresponding value. If the key is not found, then this method returns nil. If the optional block is given and the key is not found, then it will pass the block and return the result of the block. hsh.delete(key) hsh.delete(key){|key|block} Example: Ruby # Ruby program to illustrate# use of delete method a = {"x" => 34, "y" => 60} # Using delete methodp a.delete("x")p a.delete("z") Output: 34 nil 9. delete_if : This method deletes the keys and their values from the hsh when the block is true. hsh.delete_if{|key, value|block} Example: Ruby # Ruby program to illustrate# use of delete_if method a = {"x" => 34, "y" => 60} # Using delete_if methodp a.delete_if {|key, value| key >= "y"} Output: {"x"=>34} 10. each : This method calls block once for each key that present in hsh and pass key and value as a parameter. hsh.each{|key, value|block} Example: Ruby # Ruby program to illustrate# use of each method a = {"x" => 34, "y" => 60} # Using each methoda.each {|key, value| puts "the value of #{key} is #{value}" } Output: the value of x is 34 the value of y is 60 11. each_key : This method calls block once for each key that present in hsh and pass the key as a parameter. hsh.each_key{|key|block} Example: Ruby # Ruby program to illustrate# use of each_key method a = { "x" => 34, "y" => 60 } # Using the each_key methoda.each_key {|key| puts key } Output: x y 12. each_pair : This method is similar to Hash#each method. hsh.each_pair{|key, value|block} 13. each_value : This method calls block once for each key that present in hsh and pass value as a parameter. hsh.each_key{|value|block} Example: Ruby # Ruby program to illustrate# use of each_value method # Using each_value methoda = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }a.each_value{|value| puts value } Output: 23 25 3432 3453 676 14.empty?: This method return true if hsh does not contain any key and value pair. Otherwise, return false. hsh.empty? 15. fetch : This method return a value from the hsh using the given key. If the key is not found then it gives result depends on following conditions: If no argument, then it will raise an exception. If the default is given the it will return the default . If an option block is present, then it will run the block and return the result of the block. fetch method does not contain any default value. When the hash is created then it will only gaze for keys that present in the hash. hsh.fetch(key[, default]) hsh.fetch(key){|key|block} 16. has_key? : This method return true if the given key is present in the hsh, otherwise, return false. hsh.has_key? Example: Ruby # Ruby program to illustrate# use of has_key? method a = {"g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676} # Using has_key? methodp a.has_key?("x")p a.has_key?("p") Output: true false 17. has_value? : This method return true if the given value is present for a key in the hsh, otherwise, return false. hsh.has_value? Example: Ruby # Ruby program to illustrate# use of has_value? method a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 } # Using has_value? methodp a.has_value?(23)p a.has_value?(234) Output: true false 18. include? : This method is similar to Hash#has_key? method. hsh.include? 19. index : This method return the key that contain the given value. If multiple key contains the given value, then it will return only a single key from all the keys and if not found then return nil. This is a Deprecated method. So we have to use Hash#key instead. hsh.index(value) 20. invert : This method returns a new hash created by hsh‘s values as keys and the keys as values. If duplicate values are found, then it will contain only a single value is key from all the values. hsh.invert Example: Ruby # Ruby program to illustrate# use of invert method a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 } # Using invert methodp a.invert Output: {23=>"g", 25=>"h", 3432=>"x", 3453=>"y", 676=>"z"} 21. key? : This method is similar to Hash#has_key?. hsh.key?(key) 22. keys : This method returns an array of keys that present in the hash. hsh.keys 23. length : This method returns the number of key and value pair from the hsh. hsh.length Example: Ruby # Ruby program to illustrate# use of length method a = {"g" => 23, "h" => 25} # Using the length methodp a.length Output: 2 24. member? : This method is similar to Hash#has_key?. hsh.member?(key) 25. merge : This method return new hash that contains the other_hsh content. If a block is specified, then each duplicate keys and their values is called from both the hashes and the value stored in the new hash. hsh.merge(other_hsh) hsh.merge(other_hsh){|key, old_value, new_value|block} Example: Ruby # Ruby program to illustrate# use of merge method a1 = { "g" => 23, "h" => 25 }a2 = { "h" => 2343, "i" => 4340 } # Using merge methodp a1.merge(a2) Output: {"g"=>23, "h"=>2343, "i"=>4340} 26. merge! : This method merges the content of one hsh into another hsh and overwrite entries with duplicate keys with those from other_hsh. hsh.merge!(other_hsh) hsh.merge!(other_hsh){|key, old_value, new_value|block} Example: Ruby # Ruby program to illustrate# use of merge! method a1 = {"g" => 23, "h" => 25}a2 = {"h" => 2343, "i" => 4340} # Using merge! methodp a1.merge!(a2) a1 = {"g" => 23, "h" => 25 } # Using merge! methodp a1.merge!(a2) {|x, y, z| y}p a1 Output: {"g"=>23, "h"=>2343, "i"=>4340} {"g"=>23, "h"=>25, "i"=>4340} {"g"=>23, "h"=>25, "i"=>4340} 27. rehash : This method recreate the hash based on the current hash value from each key. If the value of the keys hash changed, then it will re-index the hsh. hsh.rehash Example: Ruby # Ruby program to illustrate# use of rehash method x = [ "x", "g" ]y = [ "y", "f" ]a = { x => 45345, y => 6756 }p a[x]p x[0] = "h"p a[x] # Using rehash methodp a.rehashp a[x] Output: 45345 "h" nil {["h", "g"]=>45345, ["y", "f"]=>6756} 45345 28. reject : This method is similar to Hash#delete_if, but it return the copy of hsh hsh.reject{|key, value|block} 29. reject! : This method is similar to Hash#delete_if, but return nil if no changes take place. hsh.reject!{|key, value|block} 30. replace : This method replace the content of hsh from other_hsh. hsh.replace(other_hsh) Example: Ruby # Ruby program to illustrate# use of replace method a = { "x" => 34, "y" => 60, "z"=>33 } # Using replace methodp a.replace({ "y" => 88, "x" => 987 }) Output: {"y"=>88, "x"=>987} 31. select : This method returns a new array that consists of a key and value pair only for which the given condition in the block is true. hsh.select{|key, value| block} Example: Ruby # Ruby program to illustrate# use of select method a = { "x" => 34, "y" => 60, "z"=>33 } # Using select methodp a.select {|g, f| g > "x"} Output: {"y"=>60, "z"=>33} 32. shift : This method remove the key and value pair from the hsh and return them as a two-item array. If the hshdoes not contain any pair then return nil. hsh.shift Example: Ruby # Ruby program to illustrate# use of shift method a = { "x" => 34, "y" => 60, "z"=>33 } # Using the shift methodp a.shiftp a Output: ["x", 34] {"y"=>60, "z"=>33} 33. size : This method is similar to Hash#length. hsh.size 34. sort : This method converts the hsh to the nested array of arrays that contains keys and their values and sort them by using Array#sort. hsh.sort hsh.sort{|a, b|block} Example: Ruby # Ruby program to illustrate# use of sort method a = { "x" => 34, "y" => 60, "z"=>33 } # Using sort methodp a.sortp a.sort {|x, y| x[1]<=>y[1]} Output: [["x", 34], ["y", 60], ["z", 33]] [["z", 33], ["x", 34], ["y", 60]] 35. store : This method is similar to Hash#[]=. hsh.store(key, value) 36. to_a : This method convert the hsh to the nested array of arrays that contains keys and their values. hsh.to_a Example: Ruby # Ruby program to illustrate# use of to_a method a = { "x" => 34, "y" => 60, "z"=>33 } # Using to_a methodp a.to_a Output: [["x", 34], ["y", 60], ["z", 33]] 37. to_s : This method convert hsh into a string. In other words, it converts the hash array, i.e. key and value pair in a string. hsh.to_s 38. update : This method is similar to Hash#merge!. hsh.update(other_hsh) hsh.update(other_hsh){|key, old_value, new_value|block} 39. value? : This method is similar to Hash#has_value?. hsh.value?(value) 40. values : This method returns an array which contains the values that present in hsh. hsh.values 41. values_at : This method returns an array that contains the values of the specified keys and also provide default values for the keys that are not found. hsh.values_at([keys]) Example: Ruby # Ruby program to illustrate# use of values_at method a = {"x" => 34, "y" => 60, "z"=>33} # Using values_at methodp a.values_at("x", "y") # Using default methoda.default = "geeks" # Using values_at methodp a.values_at("x", "y", "z", "g") Output: [34, 60] [34, 60, 33, "geeks"] Reference: https://docs.ruby-lang.org/en/2.0.0/Hash.html nidhi_biet kk9826225 as5853535 Ruby-Built-in-class Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Enumerator each_with_index function Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Enumerable find() function Ruby | pop() function Ruby | Types of Variables Ruby | Class Method and Variables Ruby | Operators Ruby | Types of Iterators Ruby | Array collect() operation Ruby | Array reverse() function
[ { "code": null, "e": 23986, "s": 23958, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24427, "s": 23986, "text": "In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order. The default value of Hashes is nil. When a user tries to access the keys which do not exist in the hash, then the nil value is returned. " }, { "code": null, "e": 24662, "s": 24427, "text": "1. [] : This method creates a new hash that is populated with the given objects. It is equivalent to creating a hash using literal {Key=>value....}. Keys and values are present in the pair so there is even number of arguments present." }, { "code": null, "e": 24682, "s": 24662, "text": "Hash[(key=>value)*]" }, { "code": null, "e": 24691, "s": 24682, "text": "Example:" }, { "code": null, "e": 24696, "s": 24691, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of []# Using []p Hash[\"x\", 30, \"y\", 19]p Hash[\"x\" => 30, \"y\" => 19]", "e": 24798, "s": 24696, "text": null }, { "code": null, "e": 24806, "s": 24798, "text": "Output:" }, { "code": null, "e": 24844, "s": 24806, "text": "{\"x\"=>30, \"y\"=>19}\n{\"x\"=>30, \"y\"=>19}" }, { "code": null, "e": 25350, "s": 24844, "text": "2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value. The values are stored in the hash (if necessary) depends upon the block. " }, { "code": null, "e": 25400, "s": 25350, "text": "Hash.new\nHash.new(obj)\nHash.new{|hash, key|block}" }, { "code": null, "e": 25409, "s": 25400, "text": "Example:" }, { "code": null, "e": 25414, "s": 25409, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of new method # Using new methoda = Hash.new(\"geeksforgeeks\")p a[\"x\"] = 40p a[\"y\"] = 49p a[\"x\"]p a[\"y\"]p a[\"z\"]", "e": 25560, "s": 25414, "text": null }, { "code": null, "e": 25569, "s": 25560, "text": "Output: " }, { "code": null, "e": 25597, "s": 25569, "text": "40\n49\n40\n49\n\"geeksforgeeks\"" }, { "code": null, "e": 25738, "s": 25597, "text": "3.try_convert : This method is used to convert obj into hash and returns hash or nil. It return nil when the obj does not convert into hash." }, { "code": null, "e": 25760, "s": 25738, "text": "Hash.try_convert(obj)" }, { "code": null, "e": 25769, "s": 25760, "text": "Example:" }, { "code": null, "e": 25774, "s": 25769, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of try_convert method # Using try_convert methodp Hash.try_convert({3=>8})p Hash.try_convert(\"3=>8\")", "e": 25909, "s": 25774, "text": null }, { "code": null, "e": 25918, "s": 25909, "text": "Output: " }, { "code": null, "e": 25929, "s": 25918, "text": "{3=>8}\nnil" }, { "code": null, "e": 26015, "s": 25929, "text": "Note: In the below-described methods, hsh variable is the instance of the Hash Class." }, { "code": null, "e": 26258, "s": 26015, "text": "1. ==: It is known as Equality. It is used to check if two hashes are equal or not. If they are equal means they contain the same number of keys and the value related to these keys are equal, then it will return true otherwise returns false. " }, { "code": null, "e": 26271, "s": 26258, "text": "hsh1 == hsh2" }, { "code": null, "e": 26280, "s": 26271, "text": "Example:" }, { "code": null, "e": 26285, "s": 26280, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of Equality a1 = {\"x\" => 4, \"y\" => 109}a2 = {\"x\" => 67, \"f\" => 78, \"z\" => 21}a3 = {\"f\" => 78, \"x\" => 67, \"z\" => 21} # Using equalityp a1 == a2p a2 == a3", "e": 26472, "s": 26285, "text": null }, { "code": null, "e": 26481, "s": 26472, "text": "Output: " }, { "code": null, "e": 26492, "s": 26481, "text": "false\ntrue" }, { "code": null, "e": 26645, "s": 26492, "text": "2. [] : It is known as Element Reference. It retrieves the value that stored in the key. If it does not find any value then it return the default value." }, { "code": null, "e": 26654, "s": 26645, "text": "hsh[key]" }, { "code": null, "e": 26663, "s": 26654, "text": "Example:" }, { "code": null, "e": 26668, "s": 26663, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of [] a = {\"x\" => 45, \"y\" => 67} # Using []p a[\"x\"]p a[\"z\"]", "e": 26762, "s": 26668, "text": null }, { "code": null, "e": 26771, "s": 26762, "text": "Output: " }, { "code": null, "e": 26778, "s": 26771, "text": "45\nnil" }, { "code": null, "e": 26888, "s": 26778, "text": "3. []= : It is known as Element Assignment. It associates the value given by value with the key given by key." }, { "code": null, "e": 26903, "s": 26888, "text": "hsh[key]=value" }, { "code": null, "e": 26912, "s": 26903, "text": "Example:" }, { "code": null, "e": 26917, "s": 26912, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of []= a = {\"x\" => 45, \"y\" => 67} # Using []=a[\"x\"]= 34a[\"z\"]= 89p a", "e": 27020, "s": 26917, "text": null }, { "code": null, "e": 27028, "s": 27020, "text": "Output:" }, { "code": null, "e": 27056, "s": 27028, "text": "{\"x\"=>34, \"y\"=>67, \"z\"=>89}" }, { "code": null, "e": 27131, "s": 27056, "text": "4. clear : This method removes all the keys and their values from the hsh." }, { "code": null, "e": 27141, "s": 27131, "text": "hsh.clear" }, { "code": null, "e": 27150, "s": 27141, "text": "Example:" }, { "code": null, "e": 27155, "s": 27150, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of clear method a = {\"x\" => 45, \"y\" => 67} # Using clear methodp a.clear", "e": 27262, "s": 27155, "text": null }, { "code": null, "e": 27270, "s": 27262, "text": "Output:" }, { "code": null, "e": 27273, "s": 27270, "text": "{}" }, { "code": null, "e": 27390, "s": 27273, "text": "5. default : This method return the default value. The value that returned by hsh[key], if key did not exist in hsh." }, { "code": null, "e": 27411, "s": 27390, "text": "hsh.default(nil=key)" }, { "code": null, "e": 27420, "s": 27411, "text": "Example:" }, { "code": null, "e": 27425, "s": 27420, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of default method a = Hash.new(\"geeksforgeeks\") # Using default methodp a.defaultp a.default(2)", "e": 27555, "s": 27425, "text": null }, { "code": null, "e": 27564, "s": 27555, "text": "Output: " }, { "code": null, "e": 27596, "s": 27564, "text": "\"geeksforgeeks\"\n\"geeksforgeeks\"" }, { "code": null, "e": 27712, "s": 27596, "text": "6. default= : This method sets the default value (the value which is returned for a key and not exists in a hash). " }, { "code": null, "e": 27728, "s": 27712, "text": "hsh.default=obj" }, { "code": null, "e": 27848, "s": 27728, "text": "7. default_proc : In this method if Hash.new was called with the block. Then it will return block otherwise return nil." }, { "code": null, "e": 27865, "s": 27848, "text": "hsh.default_proc" }, { "code": null, "e": 27874, "s": 27865, "text": "Example:" }, { "code": null, "e": 27879, "s": 27874, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of default_proc method a = Hash.new {|a, v| a[v] = v*v*v} # Using default_proc methodb = a.default_procc = []p b.call(c, 2)p c ", "e": 28041, "s": 27879, "text": null }, { "code": null, "e": 28050, "s": 28041, "text": "Output: " }, { "code": null, "e": 28066, "s": 28050, "text": "8\n[nil, nil, 8]" }, { "code": null, "e": 28358, "s": 28066, "text": "8. delete :This method is used to delete the entry from hash whose key is key by returning the corresponding value. If the key is not found, then this method returns nil. If the optional block is given and the key is not found, then it will pass the block and return the result of the block." }, { "code": null, "e": 28402, "s": 28358, "text": "hsh.delete(key)\nhsh.delete(key){|key|block}" }, { "code": null, "e": 28411, "s": 28402, "text": "Example:" }, { "code": null, "e": 28416, "s": 28411, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of delete method a = {\"x\" => 34, \"y\" => 60} # Using delete methodp a.delete(\"x\")p a.delete(\"z\")", "e": 28546, "s": 28416, "text": null }, { "code": null, "e": 28555, "s": 28546, "text": "Output: " }, { "code": null, "e": 28562, "s": 28555, "text": "34\nnil" }, { "code": null, "e": 28660, "s": 28562, "text": "9. delete_if : This method deletes the keys and their values from the hsh when the block is true." }, { "code": null, "e": 28693, "s": 28660, "text": "hsh.delete_if{|key, value|block}" }, { "code": null, "e": 28702, "s": 28693, "text": "Example:" }, { "code": null, "e": 28707, "s": 28702, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of delete_if method a = {\"x\" => 34, \"y\" => 60} # Using delete_if methodp a.delete_if {|key, value| key >= \"y\"}", "e": 28852, "s": 28707, "text": null }, { "code": null, "e": 28860, "s": 28852, "text": "Output:" }, { "code": null, "e": 28870, "s": 28860, "text": "{\"x\"=>34}" }, { "code": null, "e": 28983, "s": 28870, "text": "10. each : This method calls block once for each key that present in hsh and pass key and value as a parameter. " }, { "code": null, "e": 29011, "s": 28983, "text": "hsh.each{|key, value|block}" }, { "code": null, "e": 29020, "s": 29011, "text": "Example:" }, { "code": null, "e": 29025, "s": 29020, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of each method a = {\"x\" => 34, \"y\" => 60} # Using each methoda.each {|key, value| puts \"the value of #{key} is #{value}\" }", "e": 29183, "s": 29025, "text": null }, { "code": null, "e": 29192, "s": 29183, "text": "Output: " }, { "code": null, "e": 29234, "s": 29192, "text": "the value of x is 34\nthe value of y is 60" }, { "code": null, "e": 29344, "s": 29234, "text": "11. each_key : This method calls block once for each key that present in hsh and pass the key as a parameter." }, { "code": null, "e": 29369, "s": 29344, "text": "hsh.each_key{|key|block}" }, { "code": null, "e": 29378, "s": 29369, "text": "Example:" }, { "code": null, "e": 29383, "s": 29378, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of each_key method a = { \"x\" => 34, \"y\" => 60 } # Using the each_key methoda.each_key {|key| puts key }", "e": 29521, "s": 29383, "text": null }, { "code": null, "e": 29530, "s": 29521, "text": "Output: " }, { "code": null, "e": 29534, "s": 29530, "text": "x\ny" }, { "code": null, "e": 29594, "s": 29534, "text": "12. each_pair : This method is similar to Hash#each method." }, { "code": null, "e": 29627, "s": 29594, "text": "hsh.each_pair{|key, value|block}" }, { "code": null, "e": 29737, "s": 29627, "text": "13. each_value : This method calls block once for each key that present in hsh and pass value as a parameter." }, { "code": null, "e": 29764, "s": 29737, "text": "hsh.each_key{|value|block}" }, { "code": null, "e": 29773, "s": 29764, "text": "Example:" }, { "code": null, "e": 29778, "s": 29773, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of each_value method # Using each_value methoda = { \"g\" => 23, \"h\" => 25, \"x\"=>3432, \"y\"=>3453, \"z\"=>676 }a.each_value{|value| puts value }", "e": 29952, "s": 29778, "text": null }, { "code": null, "e": 29961, "s": 29952, "text": "Output: " }, { "code": null, "e": 29981, "s": 29961, "text": "23\n25\n3432\n3453\n676" }, { "code": null, "e": 30090, "s": 29981, "text": "14.empty?: This method return true if hsh does not contain any key and value pair. Otherwise, return false. " }, { "code": null, "e": 30101, "s": 30090, "text": "hsh.empty?" }, { "code": null, "e": 30252, "s": 30101, "text": "15. fetch : This method return a value from the hsh using the given key. If the key is not found then it gives result depends on following conditions:" }, { "code": null, "e": 30301, "s": 30252, "text": "If no argument, then it will raise an exception." }, { "code": null, "e": 30358, "s": 30301, "text": "If the default is given the it will return the default ." }, { "code": null, "e": 30452, "s": 30358, "text": "If an option block is present, then it will run the block and return the result of the block." }, { "code": null, "e": 30584, "s": 30452, "text": "fetch method does not contain any default value. When the hash is created then it will only gaze for keys that present in the hash." }, { "code": null, "e": 30637, "s": 30584, "text": "hsh.fetch(key[, default])\nhsh.fetch(key){|key|block}" }, { "code": null, "e": 30741, "s": 30637, "text": "16. has_key? : This method return true if the given key is present in the hsh, otherwise, return false." }, { "code": null, "e": 30754, "s": 30741, "text": "hsh.has_key?" }, { "code": null, "e": 30763, "s": 30754, "text": "Example:" }, { "code": null, "e": 30768, "s": 30763, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of has_key? method a = {\"g\" => 23, \"h\" => 25, \"x\"=>3432, \"y\"=>3453, \"z\"=>676} # Using has_key? methodp a.has_key?(\"x\")p a.has_key?(\"p\")", "e": 30938, "s": 30768, "text": null }, { "code": null, "e": 30947, "s": 30938, "text": "Output: " }, { "code": null, "e": 30958, "s": 30947, "text": "true\nfalse" }, { "code": null, "e": 31076, "s": 30958, "text": "17. has_value? : This method return true if the given value is present for a key in the hsh, otherwise, return false." }, { "code": null, "e": 31091, "s": 31076, "text": "hsh.has_value?" }, { "code": null, "e": 31100, "s": 31091, "text": "Example:" }, { "code": null, "e": 31105, "s": 31100, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of has_value? method a = { \"g\" => 23, \"h\" => 25, \"x\"=>3432, \"y\"=>3453, \"z\"=>676 } # Using has_value? methodp a.has_value?(23)p a.has_value?(234)", "e": 31284, "s": 31105, "text": null }, { "code": null, "e": 31293, "s": 31284, "text": "Output: " }, { "code": null, "e": 31304, "s": 31293, "text": "true\nfalse" }, { "code": null, "e": 31367, "s": 31304, "text": "18. include? : This method is similar to Hash#has_key? method." }, { "code": null, "e": 31380, "s": 31367, "text": "hsh.include?" }, { "code": null, "e": 31646, "s": 31380, "text": "19. index : This method return the key that contain the given value. If multiple key contains the given value, then it will return only a single key from all the keys and if not found then return nil. This is a Deprecated method. So we have to use Hash#key instead." }, { "code": null, "e": 31663, "s": 31646, "text": "hsh.index(value)" }, { "code": null, "e": 31864, "s": 31663, "text": "20. invert : This method returns a new hash created by hsh‘s values as keys and the keys as values. If duplicate values are found, then it will contain only a single value is key from all the values. " }, { "code": null, "e": 31875, "s": 31864, "text": "hsh.invert" }, { "code": null, "e": 31885, "s": 31875, "text": "Example: " }, { "code": null, "e": 31890, "s": 31885, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of invert method a = { \"g\" => 23, \"h\" => 25, \"x\"=>3432, \"y\"=>3453, \"z\"=>676 } # Using invert methodp a.invert", "e": 32034, "s": 31890, "text": null }, { "code": null, "e": 32043, "s": 32034, "text": "Output: " }, { "code": null, "e": 32094, "s": 32043, "text": "{23=>\"g\", 25=>\"h\", 3432=>\"x\", 3453=>\"y\", 676=>\"z\"}" }, { "code": null, "e": 32146, "s": 32094, "text": "21. key? : This method is similar to Hash#has_key?." }, { "code": null, "e": 32160, "s": 32146, "text": "hsh.key?(key)" }, { "code": null, "e": 32234, "s": 32160, "text": "22. keys : This method returns an array of keys that present in the hash." }, { "code": null, "e": 32243, "s": 32234, "text": "hsh.keys" }, { "code": null, "e": 32323, "s": 32243, "text": "23. length : This method returns the number of key and value pair from the hsh." }, { "code": null, "e": 32334, "s": 32323, "text": "hsh.length" }, { "code": null, "e": 32343, "s": 32334, "text": "Example:" }, { "code": null, "e": 32348, "s": 32343, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of length method a = {\"g\" => 23, \"h\" => 25} # Using the length methodp a.length", "e": 32462, "s": 32348, "text": null }, { "code": null, "e": 32471, "s": 32462, "text": "Output: " }, { "code": null, "e": 32473, "s": 32471, "text": "2" }, { "code": null, "e": 32528, "s": 32473, "text": "24. member? : This method is similar to Hash#has_key?." }, { "code": null, "e": 32545, "s": 32528, "text": "hsh.member?(key)" }, { "code": null, "e": 32758, "s": 32545, "text": "25. merge : This method return new hash that contains the other_hsh content. If a block is specified, then each duplicate keys and their values is called from both the hashes and the value stored in the new hash." }, { "code": null, "e": 32834, "s": 32758, "text": "hsh.merge(other_hsh)\nhsh.merge(other_hsh){|key, old_value, new_value|block}" }, { "code": null, "e": 32843, "s": 32834, "text": "Example:" }, { "code": null, "e": 32848, "s": 32843, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of merge method a1 = { \"g\" => 23, \"h\" => 25 }a2 = { \"h\" => 2343, \"i\" => 4340 } # Using merge methodp a1.merge(a2)", "e": 32996, "s": 32848, "text": null }, { "code": null, "e": 33004, "s": 32996, "text": "Output:" }, { "code": null, "e": 33037, "s": 33004, "text": " {\"g\"=>23, \"h\"=>2343, \"i\"=>4340}" }, { "code": null, "e": 33178, "s": 33037, "text": "26. merge! : This method merges the content of one hsh into another hsh and overwrite entries with duplicate keys with those from other_hsh." }, { "code": null, "e": 33256, "s": 33178, "text": "hsh.merge!(other_hsh)\nhsh.merge!(other_hsh){|key, old_value, new_value|block}" }, { "code": null, "e": 33265, "s": 33256, "text": "Example:" }, { "code": null, "e": 33270, "s": 33265, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of merge! method a1 = {\"g\" => 23, \"h\" => 25}a2 = {\"h\" => 2343, \"i\" => 4340} # Using merge! methodp a1.merge!(a2) a1 = {\"g\" => 23, \"h\" => 25 } # Using merge! methodp a1.merge!(a2) {|x, y, z| y}p a1", "e": 33501, "s": 33270, "text": null }, { "code": null, "e": 33510, "s": 33501, "text": "Output: " }, { "code": null, "e": 33602, "s": 33510, "text": "{\"g\"=>23, \"h\"=>2343, \"i\"=>4340}\n{\"g\"=>23, \"h\"=>25, \"i\"=>4340}\n{\"g\"=>23, \"h\"=>25, \"i\"=>4340}" }, { "code": null, "e": 33762, "s": 33602, "text": "27. rehash : This method recreate the hash based on the current hash value from each key. If the value of the keys hash changed, then it will re-index the hsh." }, { "code": null, "e": 33773, "s": 33762, "text": "hsh.rehash" }, { "code": null, "e": 33782, "s": 33773, "text": "Example:" }, { "code": null, "e": 33787, "s": 33782, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of rehash method x = [ \"x\", \"g\" ]y = [ \"y\", \"f\" ]a = { x => 45345, y => 6756 }p a[x]p x[0] = \"h\"p a[x] # Using rehash methodp a.rehashp a[x]", "e": 33962, "s": 33787, "text": null }, { "code": null, "e": 33971, "s": 33962, "text": "Output: " }, { "code": null, "e": 34029, "s": 33971, "text": "45345\n\"h\"\nnil\n{[\"h\", \"g\"]=>45345, [\"y\", \"f\"]=>6756}\n45345" }, { "code": null, "e": 34115, "s": 34029, "text": "28. reject : This method is similar to Hash#delete_if, but it return the copy of hsh " }, { "code": null, "e": 34145, "s": 34115, "text": "hsh.reject{|key, value|block}" }, { "code": null, "e": 34242, "s": 34145, "text": "29. reject! : This method is similar to Hash#delete_if, but return nil if no changes take place." }, { "code": null, "e": 34273, "s": 34242, "text": "hsh.reject!{|key, value|block}" }, { "code": null, "e": 34342, "s": 34273, "text": "30. replace : This method replace the content of hsh from other_hsh." }, { "code": null, "e": 34365, "s": 34342, "text": "hsh.replace(other_hsh)" }, { "code": null, "e": 34374, "s": 34365, "text": "Example:" }, { "code": null, "e": 34379, "s": 34374, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of replace method a = { \"x\" => 34, \"y\" => 60, \"z\"=>33 } # Using replace methodp a.replace({ \"y\" => 88, \"x\" => 987 })", "e": 34530, "s": 34379, "text": null }, { "code": null, "e": 34539, "s": 34530, "text": "Output: " }, { "code": null, "e": 34559, "s": 34539, "text": "{\"y\"=>88, \"x\"=>987}" }, { "code": null, "e": 34699, "s": 34559, "text": "31. select : This method returns a new array that consists of a key and value pair only for which the given condition in the block is true." }, { "code": null, "e": 34730, "s": 34699, "text": "hsh.select{|key, value| block}" }, { "code": null, "e": 34739, "s": 34730, "text": "Example:" }, { "code": null, "e": 34744, "s": 34739, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of select method a = { \"x\" => 34, \"y\" => 60, \"z\"=>33 } # Using select methodp a.select {|g, f| g > \"x\"}", "e": 34882, "s": 34744, "text": null }, { "code": null, "e": 34891, "s": 34882, "text": "Output: " }, { "code": null, "e": 34910, "s": 34891, "text": "{\"y\"=>60, \"z\"=>33}" }, { "code": null, "e": 35067, "s": 34910, "text": "32. shift : This method remove the key and value pair from the hsh and return them as a two-item array. If the hshdoes not contain any pair then return nil." }, { "code": null, "e": 35077, "s": 35067, "text": "hsh.shift" }, { "code": null, "e": 35086, "s": 35077, "text": "Example:" }, { "code": null, "e": 35091, "s": 35086, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of shift method a = { \"x\" => 34, \"y\" => 60, \"z\"=>33 } # Using the shift methodp a.shiftp a", "e": 35216, "s": 35091, "text": null }, { "code": null, "e": 35224, "s": 35216, "text": "Output:" }, { "code": null, "e": 35253, "s": 35224, "text": "[\"x\", 34]\n{\"y\"=>60, \"z\"=>33}" }, { "code": null, "e": 35303, "s": 35253, "text": "33. size : This method is similar to Hash#length." }, { "code": null, "e": 35312, "s": 35303, "text": "hsh.size" }, { "code": null, "e": 35453, "s": 35312, "text": "34. sort : This method converts the hsh to the nested array of arrays that contains keys and their values and sort them by using Array#sort." }, { "code": null, "e": 35484, "s": 35453, "text": "hsh.sort\nhsh.sort{|a, b|block}" }, { "code": null, "e": 35493, "s": 35484, "text": "Example:" }, { "code": null, "e": 35498, "s": 35493, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of sort method a = { \"x\" => 34, \"y\" => 60, \"z\"=>33 } # Using sort methodp a.sortp a.sort {|x, y| x[1]<=>y[1]}", "e": 35642, "s": 35498, "text": null }, { "code": null, "e": 35651, "s": 35642, "text": "Output: " }, { "code": null, "e": 35719, "s": 35651, "text": "[[\"x\", 34], [\"y\", 60], [\"z\", 33]]\n[[\"z\", 33], [\"x\", 34], [\"y\", 60]]" }, { "code": null, "e": 35767, "s": 35719, "text": "35. store : This method is similar to Hash#[]=." }, { "code": null, "e": 35789, "s": 35767, "text": "hsh.store(key, value)" }, { "code": null, "e": 35895, "s": 35789, "text": "36. to_a : This method convert the hsh to the nested array of arrays that contains keys and their values." }, { "code": null, "e": 35904, "s": 35895, "text": "hsh.to_a" }, { "code": null, "e": 35913, "s": 35904, "text": "Example:" }, { "code": null, "e": 35918, "s": 35913, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of to_a method a = { \"x\" => 34, \"y\" => 60, \"z\"=>33 } # Using to_a methodp a.to_a", "e": 36033, "s": 35918, "text": null }, { "code": null, "e": 36042, "s": 36033, "text": "Output: " }, { "code": null, "e": 36076, "s": 36042, "text": "[[\"x\", 34], [\"y\", 60], [\"z\", 33]]" }, { "code": null, "e": 36207, "s": 36076, "text": "37. to_s : This method convert hsh into a string. In other words, it converts the hash array, i.e. key and value pair in a string." }, { "code": null, "e": 36216, "s": 36207, "text": "hsh.to_s" }, { "code": null, "e": 36268, "s": 36216, "text": "38. update : This method is similar to Hash#merge!." }, { "code": null, "e": 36346, "s": 36268, "text": "hsh.update(other_hsh)\nhsh.update(other_hsh){|key, old_value, new_value|block}" }, { "code": null, "e": 36402, "s": 36346, "text": "39. value? : This method is similar to Hash#has_value?." }, { "code": null, "e": 36420, "s": 36402, "text": "hsh.value?(value)" }, { "code": null, "e": 36509, "s": 36420, "text": "40. values : This method returns an array which contains the values that present in hsh." }, { "code": null, "e": 36520, "s": 36509, "text": "hsh.values" }, { "code": null, "e": 36677, "s": 36520, "text": "41. values_at : This method returns an array that contains the values of the specified keys and also provide default values for the keys that are not found." }, { "code": null, "e": 36699, "s": 36677, "text": "hsh.values_at([keys])" }, { "code": null, "e": 36708, "s": 36699, "text": "Example:" }, { "code": null, "e": 36713, "s": 36708, "text": "Ruby" }, { "code": "# Ruby program to illustrate# use of values_at method a = {\"x\" => 34, \"y\" => 60, \"z\"=>33} # Using values_at methodp a.values_at(\"x\", \"y\") # Using default methoda.default = \"geeks\" # Using values_at methodp a.values_at(\"x\", \"y\", \"z\", \"g\")", "e": 36951, "s": 36713, "text": null }, { "code": null, "e": 36960, "s": 36951, "text": "Output: " }, { "code": null, "e": 36991, "s": 36960, "text": "[34, 60]\n[34, 60, 33, \"geeks\"]" }, { "code": null, "e": 37049, "s": 36991, "text": "Reference: https://docs.ruby-lang.org/en/2.0.0/Hash.html " }, { "code": null, "e": 37060, "s": 37049, "text": "nidhi_biet" }, { "code": null, "e": 37070, "s": 37060, "text": "kk9826225" }, { "code": null, "e": 37080, "s": 37070, "text": "as5853535" }, { "code": null, "e": 37100, "s": 37080, "text": "Ruby-Built-in-class" }, { "code": null, "e": 37105, "s": 37100, "text": "Ruby" }, { "code": null, "e": 37203, "s": 37105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37212, "s": 37203, "text": "Comments" }, { "code": null, "e": 37225, "s": 37212, "text": "Old Comments" }, { "code": null, "e": 37268, "s": 37225, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 37336, "s": 37268, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 37370, "s": 37336, "text": "Ruby | Enumerable find() function" }, { "code": null, "e": 37392, "s": 37370, "text": "Ruby | pop() function" }, { "code": null, "e": 37418, "s": 37392, "text": "Ruby | Types of Variables" }, { "code": null, "e": 37452, "s": 37418, "text": "Ruby | Class Method and Variables" }, { "code": null, "e": 37469, "s": 37452, "text": "Ruby | Operators" }, { "code": null, "e": 37495, "s": 37469, "text": "Ruby | Types of Iterators" }, { "code": null, "e": 37528, "s": 37495, "text": "Ruby | Array collect() operation" } ]
An Interesting Method to Generate Binary Numbers from 1 to n?
Here we will see one interesting method for generating binary numbers from 1 to n. Here we are using queue. Initially the queue will hold first binary number ‘1’. Now repeatedly delete element from queue, and print it, and append 0 at the end of the front item, and append 1 at the end of the front time, and insert them into the queue. Let us see the algorithm to get the idea. Begin define empty queue. insert 1 into the queue while n is not 0, do delete element from queue and store it into s1 print s1 s2 := s1 insert s1 by adding 0 after it into queue insert s1 by adding 1 after it into queue decrease n by 1 done End #include <iostream> #include <queue> using namespace std; void genBinaryNumbers(int n){ queue<string> qu; qu.push("1"); while(n != 0){ string s1 = qu.front(); qu.pop(); cout << s1 << " "; string s2 = s1; qu.push(s1 + "0"); qu.push(s1 + "1"); n--; } } int main() { int n = 15; genBinaryNumbers(n); } 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
[ { "code": null, "e": 1441, "s": 1062, "text": "Here we will see one interesting method for generating binary numbers from 1 to n. Here we are using queue. Initially the queue will hold first binary number ‘1’. Now repeatedly delete element from queue, and print it, and append 0 at the end of the front item, and append 1 at the end of the front time, and insert them into the queue. Let us see the algorithm to get the idea." }, { "code": null, "e": 1734, "s": 1441, "text": "Begin\n define empty queue.\n insert 1 into the queue\n while n is not 0, do\n delete element from queue and store it into s1\n print s1\n s2 := s1\n insert s1 by adding 0 after it into queue\n insert s1 by adding 1 after it into queue\n decrease n by 1\n done\nEnd" }, { "code": null, "e": 2093, "s": 1734, "text": "#include <iostream>\n#include <queue>\nusing namespace std;\nvoid genBinaryNumbers(int n){\n queue<string> qu;\n qu.push(\"1\");\n while(n != 0){\n string s1 = qu.front();\n qu.pop();\n cout << s1 << \" \";\n string s2 = s1;\n qu.push(s1 + \"0\");\n qu.push(s1 + \"1\");\n n--;\n }\n}\nint main() {\n int n = 15;\n genBinaryNumbers(n);\n}" }, { "code": null, "e": 2157, "s": 2093, "text": "1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111" } ]
How to secure Python Flask Web APIs with Azure AD | by René Bremer | Towards Data Science
Python Flask is a popular tool to create web applications. Using Azure AD, users can authenticate to the REST APIs and retrieve data from Azure SQL. In this blog, a sample Python web application is created as follows: 1a: User logs in to web app and acquires a token 1b: User calls a REST API to request a dataset 2: Web app uses claims in token to verify user access to dataset 3: Web app retrieves data from Azure SQL. Web app can be configured such that either the a) managed identity of the app or b) signed-in user identity is used for authentication to the database The code of the project can be found here, architecture can be found below. In the remaining of this blog, the following steps are executed: Step 1: Acquire token and call api using token Step 2: Verify claims in token Step 3a: App managed identity authentication Step 3b: Signed-in user passthrough authentication To learn how to access an Azure Function backend using delegated or application permissions, see my follow-up blog which shares the same git repo as this blog. This sample shows how to build a Python web app using Flask and MSAL Python, that signs in a user, and get access to Azure SQL Database. For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD. In this step, the following sub steps are executed: 1.1: Preliminaries 1.2: Create and configure app registration 1.3: Configure the python webapp project 1.4: Run the sample Step 1 focusses on the follow part of the architecture. To run this sample, you’ll need: Python 2.7+ or Python 3+ An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see how to get an Azure AD tenant. Git to clone the following project: git clone https://github.com/rebremer/ms-identity-python-webapp-backend.gitor download and extract the repository .zip file. Create and configure an app registration as follows: Create an app registration using the steps in this link to create an app registration. Two remarks: Use http://localhost/getAToken as reply URL. In case you did not do this during creation, it can be added using the Authentication tab of the app registration Go to Authentication and enable the option ID tokens in Implicit grant Go to Certificates & Secrets to create a secret. Copy the client_id and client secret Open the app_config.py file and change the variables below.Find text <<Enter_the_Client_Secret_here>> and replace it with your application secret during the creation of the app registration in step 1.2.Find text <<Enter_the_Tenant_Name_Here>> and replace the existing value with your Azure AD tenant name.Find text <<Enter_the_Application_Id_here>> and replace the existing value with the application ID (clientId) of the app registration in step 1.2. Open the app_config.py file and change the variables below. Find text <<Enter_the_Client_Secret_here>> and replace it with your application secret during the creation of the app registration in step 1.2. Find text <<Enter_the_Tenant_Name_Here>> and replace the existing value with your Azure AD tenant name. Find text <<Enter_the_Application_Id_here>> and replace the existing value with the application ID (clientId) of the app registration in step 1.2. You will need to install dependencies using pip as follows: $ pip install -r requirements.txt Run app.py from shell or command line using the following command: flask run --host localhost --port 5000 When the app is run locally, it can be visited by localhost:5000 (not 127.0.0.1:5000). After step 1, users can login using their Azure AD credentials. In the next step, the user roles are set that can be used to verify if user is allowed to retrieve data using the API. In this step, the claims in the tokens can be set which can be just be the web app to verify whether a user is allowed to call an api. See this link for more information on token claims. The following sub steps are executed: 2.1: Set configuration in app config 2.2: Add roles to manifest 2.3: Assign user to role Step 2 focusses on the follow part of the architecture. Claim verification is an optional step and can be enabled using the following setting in app_config.py file: AAD_ROLE_CHECK = True . Follow the steps in this tutorial to add roles to app registration created in step 1.2. As manifest, the following appRoles shall be used: "appRoles": [ { "allowedMemberTypes": ["User"], "description": "Basic user, only read product data from SQLDB", "displayName": "basic_user_access", "id": "a8161423-2e8e-46c4-9997-f984faccb625", "isEnabled": true, "value": "basic_user_access" }, { "allowedMemberTypes": ["User"], "description": "Premium user, read all data from SQLDB", "displayName": "premium_user_access", "id": "b8161423-2e8e-46c4-9997-f984faccb625", "isEnabled": true, "value": "premium_user_access" }], The assignment of users is explained in th link. As a test, two users can be created. User 1 is assigned the basic_user_access, whereas user 2 gets the premium_user_access role. In the next step, the Azure SQL database is created and the application identity is used to retrieve data form the database. In this step, the managed identity of the app is used to retrieve data, which is linked to the app registration created in step 1. The following sub steps are executed: 3a.1: Create Azure SQL database 3a.2: Set configuration in app config Step 3a focusses on the follow part of the architecture. Create an Azure SQL DB using this link in which the cheapest SKU (basic) can be selected. Make sure the following is done: AdvertureWorks is installed as sample database, the cheapest database can be selected (SKU basic). Add app identity as user to Azure SQL database with correct reader roles, see example below as follows CREATE USER [<<Name of app registration>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<Name of app registration>>]; The backend_settings needs to be set to database. Make also sure that connection is filled in with your settings. Since the MI of the app is used, application_permissions need to point to “https://database.windows.net//.default" in the app_config.py file, see also below. # 2. Type of BACKEND## Option 2a. DatabaseBACKEND_SETTINGS = {"Type": "Database", "Connection":{"SQL_SERVER": "<<Enter_logical_SQL_server_URL_here>>.database.windows.net", "DATABASE": "<<Enter_SQL_database_name_here>>"}}# Option 3a. Delegated user is used to authenticate to Graph API, MI is then used to authenticate to backend...APPLICATION_PERMISSIONS = ["https://database.windows.net//.default"] Now the app can be run as described in step 1.4. When you click on the link (Premium users only) Get Customer data from Database , customer data is retrieved. Subsequently, when there is clicked on the link Get Product data from Database, product data is retrieved (provided that claims are set correctly for user in step 2 or check is disabled) In this step, the identity of the app is used to retrieve data. However, the identity of the user can also passed (AAD passthrough) to retrieve data from the database. In the step, the identity of the user itself is used to retrieve data. This means that the token created in step 1 to login in the web app is also used to authenticate to the database. The following sub steps are executed: 3b.1: Add Azure SQL DB Scope to app registration 3b.2: Add AAD user to database 3b.3: Set configuration in app config Step 3b focusses on the follow part of the architecture. Modify your app registration created in step 1.2. with permissions for Azure SQL database as delegated user. This is explained in this link Important: Admin consent is required for Azure SQL Database. This can be either done by selecting Grant_admin consent for Default Directory in the permissions tab or at runtime while logging in Since AAD passthrough is used in this step, the users themselves shall have the appropriate roles in the SQLDB as external user and datareader. See example how to do this below. CREATE USER [<<AAD user email address>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<AAD user email address>>]; In case you want to be more granular in rolemembers in the database, read_customer reads data from SalesLT.Customer, whereas read_product reads data from SalesLT.Product) AAD User passthrough authentication can be set in the app_config.py file by setting delegated_permissions to [“https://sql.azuresynapse-dogfood.net/user_impersonation"], see also below # Option 3b. Delegated user is used to authenticate to backend, graph API disabled...DELEGATED_PERMISSONS = ["https://sql.azuresynapse-dogfood.net/user_impersonation"] Now the app can be run as described in step 1.4, in which data can be retrieved from the database using the identity of the logged in user. In this blog, a Python web application is created that retrieves data from SQLDB. Users claims, managed identities and signed-in user passthrough tokens are discussed to authenticate and authorize users to retrieve data from Azure SQL, see also overview below.
[ { "code": null, "e": 389, "s": 171, "text": "Python Flask is a popular tool to create web applications. Using Azure AD, users can authenticate to the REST APIs and retrieve data from Azure SQL. In this blog, a sample Python web application is created as follows:" }, { "code": null, "e": 438, "s": 389, "text": "1a: User logs in to web app and acquires a token" }, { "code": null, "e": 485, "s": 438, "text": "1b: User calls a REST API to request a dataset" }, { "code": null, "e": 550, "s": 485, "text": "2: Web app uses claims in token to verify user access to dataset" }, { "code": null, "e": 743, "s": 550, "text": "3: Web app retrieves data from Azure SQL. Web app can be configured such that either the a) managed identity of the app or b) signed-in user identity is used for authentication to the database" }, { "code": null, "e": 819, "s": 743, "text": "The code of the project can be found here, architecture can be found below." }, { "code": null, "e": 884, "s": 819, "text": "In the remaining of this blog, the following steps are executed:" }, { "code": null, "e": 931, "s": 884, "text": "Step 1: Acquire token and call api using token" }, { "code": null, "e": 962, "s": 931, "text": "Step 2: Verify claims in token" }, { "code": null, "e": 1007, "s": 962, "text": "Step 3a: App managed identity authentication" }, { "code": null, "e": 1058, "s": 1007, "text": "Step 3b: Signed-in user passthrough authentication" }, { "code": null, "e": 1218, "s": 1058, "text": "To learn how to access an Azure Function backend using delegated or application permissions, see my follow-up blog which shares the same git repo as this blog." }, { "code": null, "e": 1538, "s": 1218, "text": "This sample shows how to build a Python web app using Flask and MSAL Python, that signs in a user, and get access to Azure SQL Database. For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD. In this step, the following sub steps are executed:" }, { "code": null, "e": 1557, "s": 1538, "text": "1.1: Preliminaries" }, { "code": null, "e": 1600, "s": 1557, "text": "1.2: Create and configure app registration" }, { "code": null, "e": 1641, "s": 1600, "text": "1.3: Configure the python webapp project" }, { "code": null, "e": 1661, "s": 1641, "text": "1.4: Run the sample" }, { "code": null, "e": 1717, "s": 1661, "text": "Step 1 focusses on the follow part of the architecture." }, { "code": null, "e": 1750, "s": 1717, "text": "To run this sample, you’ll need:" }, { "code": null, "e": 1775, "s": 1750, "text": "Python 2.7+ or Python 3+" }, { "code": null, "e": 1910, "s": 1775, "text": "An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see how to get an Azure AD tenant." }, { "code": null, "e": 2071, "s": 1910, "text": "Git to clone the following project: git clone https://github.com/rebremer/ms-identity-python-webapp-backend.gitor download and extract the repository .zip file." }, { "code": null, "e": 2124, "s": 2071, "text": "Create and configure an app registration as follows:" }, { "code": null, "e": 2224, "s": 2124, "text": "Create an app registration using the steps in this link to create an app registration. Two remarks:" }, { "code": null, "e": 2383, "s": 2224, "text": "Use http://localhost/getAToken as reply URL. In case you did not do this during creation, it can be added using the Authentication tab of the app registration" }, { "code": null, "e": 2454, "s": 2383, "text": "Go to Authentication and enable the option ID tokens in Implicit grant" }, { "code": null, "e": 2540, "s": 2454, "text": "Go to Certificates & Secrets to create a secret. Copy the client_id and client secret" }, { "code": null, "e": 2992, "s": 2540, "text": "Open the app_config.py file and change the variables below.Find text <<Enter_the_Client_Secret_here>> and replace it with your application secret during the creation of the app registration in step 1.2.Find text <<Enter_the_Tenant_Name_Here>> and replace the existing value with your Azure AD tenant name.Find text <<Enter_the_Application_Id_here>> and replace the existing value with the application ID (clientId) of the app registration in step 1.2." }, { "code": null, "e": 3052, "s": 2992, "text": "Open the app_config.py file and change the variables below." }, { "code": null, "e": 3196, "s": 3052, "text": "Find text <<Enter_the_Client_Secret_here>> and replace it with your application secret during the creation of the app registration in step 1.2." }, { "code": null, "e": 3300, "s": 3196, "text": "Find text <<Enter_the_Tenant_Name_Here>> and replace the existing value with your Azure AD tenant name." }, { "code": null, "e": 3447, "s": 3300, "text": "Find text <<Enter_the_Application_Id_here>> and replace the existing value with the application ID (clientId) of the app registration in step 1.2." }, { "code": null, "e": 3507, "s": 3447, "text": "You will need to install dependencies using pip as follows:" }, { "code": null, "e": 3541, "s": 3507, "text": "$ pip install -r requirements.txt" }, { "code": null, "e": 3608, "s": 3541, "text": "Run app.py from shell or command line using the following command:" }, { "code": null, "e": 3647, "s": 3608, "text": "flask run --host localhost --port 5000" }, { "code": null, "e": 3917, "s": 3647, "text": "When the app is run locally, it can be visited by localhost:5000 (not 127.0.0.1:5000). After step 1, users can login using their Azure AD credentials. In the next step, the user roles are set that can be used to verify if user is allowed to retrieve data using the API." }, { "code": null, "e": 4142, "s": 3917, "text": "In this step, the claims in the tokens can be set which can be just be the web app to verify whether a user is allowed to call an api. See this link for more information on token claims. The following sub steps are executed:" }, { "code": null, "e": 4179, "s": 4142, "text": "2.1: Set configuration in app config" }, { "code": null, "e": 4206, "s": 4179, "text": "2.2: Add roles to manifest" }, { "code": null, "e": 4231, "s": 4206, "text": "2.3: Assign user to role" }, { "code": null, "e": 4287, "s": 4231, "text": "Step 2 focusses on the follow part of the architecture." }, { "code": null, "e": 4420, "s": 4287, "text": "Claim verification is an optional step and can be enabled using the following setting in app_config.py file: AAD_ROLE_CHECK = True ." }, { "code": null, "e": 4559, "s": 4420, "text": "Follow the steps in this tutorial to add roles to app registration created in step 1.2. As manifest, the following appRoles shall be used:" }, { "code": null, "e": 5073, "s": 4559, "text": "\"appRoles\": [ { \"allowedMemberTypes\": [\"User\"], \"description\": \"Basic user, only read product data from SQLDB\", \"displayName\": \"basic_user_access\", \"id\": \"a8161423-2e8e-46c4-9997-f984faccb625\", \"isEnabled\": true, \"value\": \"basic_user_access\" }, { \"allowedMemberTypes\": [\"User\"], \"description\": \"Premium user, read all data from SQLDB\", \"displayName\": \"premium_user_access\", \"id\": \"b8161423-2e8e-46c4-9997-f984faccb625\", \"isEnabled\": true, \"value\": \"premium_user_access\" }]," }, { "code": null, "e": 5251, "s": 5073, "text": "The assignment of users is explained in th link. As a test, two users can be created. User 1 is assigned the basic_user_access, whereas user 2 gets the premium_user_access role." }, { "code": null, "e": 5376, "s": 5251, "text": "In the next step, the Azure SQL database is created and the application identity is used to retrieve data form the database." }, { "code": null, "e": 5545, "s": 5376, "text": "In this step, the managed identity of the app is used to retrieve data, which is linked to the app registration created in step 1. The following sub steps are executed:" }, { "code": null, "e": 5577, "s": 5545, "text": "3a.1: Create Azure SQL database" }, { "code": null, "e": 5615, "s": 5577, "text": "3a.2: Set configuration in app config" }, { "code": null, "e": 5672, "s": 5615, "text": "Step 3a focusses on the follow part of the architecture." }, { "code": null, "e": 5795, "s": 5672, "text": "Create an Azure SQL DB using this link in which the cheapest SKU (basic) can be selected. Make sure the following is done:" }, { "code": null, "e": 5894, "s": 5795, "text": "AdvertureWorks is installed as sample database, the cheapest database can be selected (SKU basic)." }, { "code": null, "e": 5997, "s": 5894, "text": "Add app identity as user to Azure SQL database with correct reader roles, see example below as follows" }, { "code": null, "e": 6134, "s": 5997, "text": "CREATE USER [<<Name of app registration>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<Name of app registration>>];" }, { "code": null, "e": 6406, "s": 6134, "text": "The backend_settings needs to be set to database. Make also sure that connection is filled in with your settings. Since the MI of the app is used, application_permissions need to point to “https://database.windows.net//.default\" in the app_config.py file, see also below." }, { "code": null, "e": 6806, "s": 6406, "text": "# 2. Type of BACKEND## Option 2a. DatabaseBACKEND_SETTINGS = {\"Type\": \"Database\", \"Connection\":{\"SQL_SERVER\": \"<<Enter_logical_SQL_server_URL_here>>.database.windows.net\", \"DATABASE\": \"<<Enter_SQL_database_name_here>>\"}}# Option 3a. Delegated user is used to authenticate to Graph API, MI is then used to authenticate to backend...APPLICATION_PERMISSIONS = [\"https://database.windows.net//.default\"]" }, { "code": null, "e": 7152, "s": 6806, "text": "Now the app can be run as described in step 1.4. When you click on the link (Premium users only) Get Customer data from Database , customer data is retrieved. Subsequently, when there is clicked on the link Get Product data from Database, product data is retrieved (provided that claims are set correctly for user in step 2 or check is disabled)" }, { "code": null, "e": 7320, "s": 7152, "text": "In this step, the identity of the app is used to retrieve data. However, the identity of the user can also passed (AAD passthrough) to retrieve data from the database." }, { "code": null, "e": 7543, "s": 7320, "text": "In the step, the identity of the user itself is used to retrieve data. This means that the token created in step 1 to login in the web app is also used to authenticate to the database. The following sub steps are executed:" }, { "code": null, "e": 7592, "s": 7543, "text": "3b.1: Add Azure SQL DB Scope to app registration" }, { "code": null, "e": 7623, "s": 7592, "text": "3b.2: Add AAD user to database" }, { "code": null, "e": 7661, "s": 7623, "text": "3b.3: Set configuration in app config" }, { "code": null, "e": 7718, "s": 7661, "text": "Step 3b focusses on the follow part of the architecture." }, { "code": null, "e": 7858, "s": 7718, "text": "Modify your app registration created in step 1.2. with permissions for Azure SQL database as delegated user. This is explained in this link" }, { "code": null, "e": 8052, "s": 7858, "text": "Important: Admin consent is required for Azure SQL Database. This can be either done by selecting Grant_admin consent for Default Directory in the permissions tab or at runtime while logging in" }, { "code": null, "e": 8230, "s": 8052, "text": "Since AAD passthrough is used in this step, the users themselves shall have the appropriate roles in the SQLDB as external user and datareader. See example how to do this below." }, { "code": null, "e": 8363, "s": 8230, "text": "CREATE USER [<<AAD user email address>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<AAD user email address>>];" }, { "code": null, "e": 8534, "s": 8363, "text": "In case you want to be more granular in rolemembers in the database, read_customer reads data from SalesLT.Customer, whereas read_product reads data from SalesLT.Product)" }, { "code": null, "e": 8719, "s": 8534, "text": "AAD User passthrough authentication can be set in the app_config.py file by setting delegated_permissions to [“https://sql.azuresynapse-dogfood.net/user_impersonation\"], see also below" }, { "code": null, "e": 8887, "s": 8719, "text": "# Option 3b. Delegated user is used to authenticate to backend, graph API disabled...DELEGATED_PERMISSONS = [\"https://sql.azuresynapse-dogfood.net/user_impersonation\"]" }, { "code": null, "e": 9027, "s": 8887, "text": "Now the app can be run as described in step 1.4, in which data can be retrieved from the database using the identity of the logged in user." } ]
How to Install iPython on Windows? - GeeksforGeeks
22 Sep, 2021 Ipython is a toolkit used for using Python interactively using a Python shell and also provides a Jupyter kernel to work with Python code in Jupyter notebooks. In this article, we will look into the process of installing ipython package on Windows. The only thing that you need for installing the Scrapy module on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c anaconda ipython Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge To verify if IPython Package has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list ipython You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the Command Prompt and use the below command: pip install ipython You will get a similar message once the installation is complete: To verify if the IPython Package has been successfully installed in your system run the below command in Command Prompt: python -m pip show ipython You’ll get the below message if the installation is complete: how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 24952, "s": 24924, "text": "\n22 Sep, 2021" }, { "code": null, "e": 25201, "s": 24952, "text": "Ipython is a toolkit used for using Python interactively using a Python shell and also provides a Jupyter kernel to work with Python code in Jupyter notebooks. In this article, we will look into the process of installing ipython package on Windows." }, { "code": null, "e": 25279, "s": 25201, "text": "The only thing that you need for installing the Scrapy module on Windows are:" }, { "code": null, "e": 25287, "s": 25279, "text": "Python " }, { "code": null, "e": 25333, "s": 25287, "text": "PIP or Conda (depending upon user preference)" }, { "code": null, "e": 25455, "s": 25333, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 25489, "s": 25455, "text": "conda install -c anaconda ipython" }, { "code": null, "e": 25519, "s": 25489, "text": "Type y for yes when prompted." }, { "code": null, "e": 25585, "s": 25519, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 25658, "s": 25585, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 25755, "s": 25658, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 25800, "s": 25755, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 25886, "s": 25800, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 25932, "s": 25886, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 26061, "s": 25932, "text": "To verify if IPython Package has been successfully installed in your system run the below command in Anaconda Powershell Prompt:" }, { "code": null, "e": 26080, "s": 26061, "text": "conda list ipython" }, { "code": null, "e": 26142, "s": 26080, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 26250, "s": 26142, "text": "If you want the installation to be done through PIP, open up the Command Prompt and use the below command:" }, { "code": null, "e": 26270, "s": 26250, "text": "pip install ipython" }, { "code": null, "e": 26336, "s": 26270, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 26458, "s": 26336, "text": "To verify if the IPython Package has been successfully installed in your system run the below command in Command Prompt:" }, { "code": null, "e": 26485, "s": 26458, "text": "python -m pip show ipython" }, { "code": null, "e": 26547, "s": 26485, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 26562, "s": 26547, "text": "how-to-install" }, { "code": null, "e": 26569, "s": 26562, "text": "Picked" }, { "code": null, "e": 26576, "s": 26569, "text": "How To" }, { "code": null, "e": 26595, "s": 26576, "text": "Installation Guide" }, { "code": null, "e": 26693, "s": 26595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26702, "s": 26693, "text": "Comments" }, { "code": null, "e": 26715, "s": 26702, "text": "Old Comments" }, { "code": null, "e": 26749, "s": 26715, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26798, "s": 26749, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26856, "s": 26798, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26916, "s": 26856, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 26958, "s": 26916, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26991, "s": 26958, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27025, "s": 26991, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27060, "s": 27025, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 27118, "s": 27060, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Stream empty() in Java with Examples
06 Dec, 2018 Stream empty() creates an empty sequential Stream. Syntax : static <T> Stream<T> empty() Parameters : T : The type of stream elements. Stream : A sequence of objects that supports various methods which can be pipelined to produce the desired result. Return Value : Stream empty() returns an empty sequential stream. Note : An empty stream might be useful to avoid null pointer exceptions while callings methods with stream parameters. Example : // Java code for Stream empty()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an empty Stream Stream<String> stream = Stream.empty(); // Displaying elements in Stream stream.forEach(System.out::println); }} Output : No Output Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 79, "s": 28, "text": "Stream empty() creates an empty sequential Stream." }, { "code": null, "e": 88, "s": 79, "text": "Syntax :" }, { "code": null, "e": 118, "s": 88, "text": "static <T> Stream<T> empty()\n" }, { "code": null, "e": 131, "s": 118, "text": "Parameters :" }, { "code": null, "e": 164, "s": 131, "text": "T : The type of stream elements." }, { "code": null, "e": 279, "s": 164, "text": "Stream : A sequence of objects that supports various methods which can be pipelined to produce the desired result." }, { "code": null, "e": 345, "s": 279, "text": "Return Value : Stream empty() returns an empty sequential stream." }, { "code": null, "e": 464, "s": 345, "text": "Note : An empty stream might be useful to avoid null pointer exceptions while callings methods with stream parameters." }, { "code": null, "e": 474, "s": 464, "text": "Example :" }, { "code": "// Java code for Stream empty()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an empty Stream Stream<String> stream = Stream.empty(); // Displaying elements in Stream stream.forEach(System.out::println); }}", "e": 810, "s": 474, "text": null }, { "code": null, "e": 819, "s": 810, "text": "Output :" }, { "code": null, "e": 830, "s": 819, "text": "No Output\n" }, { "code": null, "e": 850, "s": 830, "text": "Java - util package" }, { "code": null, "e": 865, "s": 850, "text": "Java-Functions" }, { "code": null, "e": 877, "s": 865, "text": "java-stream" }, { "code": null, "e": 899, "s": 877, "text": "Java-Stream interface" }, { "code": null, "e": 904, "s": 899, "text": "Java" }, { "code": null, "e": 909, "s": 904, "text": "Java" } ]
Create First GUI Application using Python-Tkinter
20 Sep, 2021 Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. Tkinter is lightweight and relatively painless to use compared to other frameworks. This makes it a compelling choice for building GUI applications in Python, especially for applications where a modern shine is unnecessary, and the top priority is to build something that’s functional and cross-platform quickly. To understand Tkinter better, we will create a simple GUI. 1. Import tkinter package and all of its modules.2. Create a root window. Give the root window a title(using title()) and dimension(using geometry()). All other widgets will be inside the root window. 3. Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will wait for any user interaction till we close it. Example: Python3 # Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")# Set geometry (widthxheight)root.geometry('350x200') # all widgets will be here# Execute Tkinterroot.mainloop() Output: Root Window 4. We’ll add a label using the Label Class and change its text configuration as desired. The grid() function is a geometry manager which keeps the label in the desired location inside the window. If no parameters are mentioned by default it will place it in the empty cell; that is 0,0 as that is the first location. Example: Python3 # Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")# Set geometry(widthxheight)root.geometry('350x200') #adding a label to the root windowlbl = Label(root, text = "Are you a Geek?")lbl.grid() # Execute Tkinterroot.mainloop() Output: Label inside root window 5. Now add a button to the root window. Changing the button configurations gives us a lot of options. In this example we will make the button display a text once it is clicked and also change the color of the text inside the button. Example: Python3 # Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")# Set geometry(widthxheight)root.geometry('350x200') # adding a label to the root windowlbl = Label(root, text = "Are you a Geek?")lbl.grid() # function to display text when# button is clickeddef clicked(): lbl.configure(text = "I just got clicked") # button widget with red color text# insidebtn = Button(root, text = "Click me" , fg = "red", command=clicked)# set Button gridbtn.grid(column=1, row=0) # Execute Tkinterroot.mainloop() Output: Button added After clicking “Click me” 6. Using the Entry() class we will create a text box for user input. To display the user input text, we’ll make changes to the function clicked(). We can get the user entered text using the get() function. When the Button after entering of the text, a default text concatenated with the user text. Also change button grid location to column 2 as Entry() will be column 1. Example: Python3 # Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")# Set geometry(widthxheight)root.geometry('350x200') # adding a label to the root windowlbl = Label(root, text = "Are you a Geek?")lbl.grid() # adding Entry Fieldtxt = Entry(root, width=10)txt.grid(column =1, row =0) # function to display user text when# button is clickeddef clicked(): res = "You wrote" + txt.get() lbl.configure(text = res) # button widget with red color text insidebtn = Button(root, text = "Click me" , fg = "red", command=clicked)# Set Button Gridbtn.grid(column=2, row=0) # Execute Tkinterroot.mainloop() Output: Entry Widget at column 2 row 0 Displaying user input text. 7. To add a menu bar, you can use Menu class. First, we create a menu, then we add our first label, and finally, we assign the menu to our window. We can add menu items under any menu by using add_cascade(). Example: Python3 # Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")# Set geometry(widthxheight)root.geometry('350x200') # adding menu bar in root window# new item in menu bar labelled as 'New'# adding more items in the menu barmenu = Menu(root)item = Menu(menu)item.add_command(label='New')menu.add_cascade(label='File', menu=item)root.config(menu=menu) # adding a label to the root windowlbl = Label(root, text = "Are you a Geek?")lbl.grid() # adding Entry Fieldtxt = Entry(root, width=10)txt.grid(column =1, row =0) # function to display user text when# button is clickeddef clicked(): res = "You wrote" + txt.get() lbl.configure(text = res) # button widget with red color text insidebtn = Button(root, text = "Click me" , fg = "red", command=clicked)# Set Button Gridbtn.grid(column=2, row=0) # Execute Tkinterroot.mainloop() Output : Menu bar This simple GUI covers the basics of Tkinter package. Similarly, you can add more widgets and change their configurations as desired. Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called Widgets. The list of commonly used Widgets are mentioned below – All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place. Their description is mentioned below – abhigoya anikakapoor kalrap615 Python-tkinter 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 Sep, 2021" }, { "code": null, "e": 648, "s": 52, "text": "Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. Tkinter is lightweight and relatively painless to use compared to other frameworks. This makes it a compelling choice for building GUI applications in Python, especially for applications where a modern shine is unnecessary, and the top priority is to build something that’s functional and cross-platform quickly. " }, { "code": null, "e": 708, "s": 648, "text": "To understand Tkinter better, we will create a simple GUI. " }, { "code": null, "e": 1092, "s": 708, "text": "1. Import tkinter package and all of its modules.2. Create a root window. Give the root window a title(using title()) and dimension(using geometry()). All other widgets will be inside the root window. 3. Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will wait for any user interaction till we close it." }, { "code": null, "e": 1101, "s": 1092, "text": "Example:" }, { "code": null, "e": 1109, "s": 1101, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")# Set geometry (widthxheight)root.geometry('350x200') # all widgets will be here# Execute Tkinterroot.mainloop()", "e": 1361, "s": 1109, "text": null }, { "code": null, "e": 1374, "s": 1364, "text": "Output: " }, { "code": null, "e": 1386, "s": 1374, "text": "Root Window" }, { "code": null, "e": 1709, "s": 1388, "text": " 4. We’ll add a label using the Label Class and change its text configuration as desired. The grid() function is a geometry manager which keeps the label in the desired location inside the window. If no parameters are mentioned by default it will place it in the empty cell; that is 0,0 as that is the first location. " }, { "code": null, "e": 1718, "s": 1709, "text": "Example:" }, { "code": null, "e": 1726, "s": 1718, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")# Set geometry(widthxheight)root.geometry('350x200') #adding a label to the root windowlbl = Label(root, text = \"Are you a Geek?\")lbl.grid() # Execute Tkinterroot.mainloop()", "e": 2039, "s": 1726, "text": null }, { "code": null, "e": 2049, "s": 2039, "text": "Output: " }, { "code": null, "e": 2074, "s": 2049, "text": "Label inside root window" }, { "code": null, "e": 2312, "s": 2076, "text": "5. Now add a button to the root window. Changing the button configurations gives us a lot of options. In this example we will make the button display a text once it is clicked and also change the color of the text inside the button. " }, { "code": null, "e": 2321, "s": 2312, "text": "Example:" }, { "code": null, "e": 2329, "s": 2321, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")# Set geometry(widthxheight)root.geometry('350x200') # adding a label to the root windowlbl = Label(root, text = \"Are you a Geek?\")lbl.grid() # function to display text when# button is clickeddef clicked(): lbl.configure(text = \"I just got clicked\") # button widget with red color text# insidebtn = Button(root, text = \"Click me\" , fg = \"red\", command=clicked)# set Button gridbtn.grid(column=1, row=0) # Execute Tkinterroot.mainloop()", "e": 2919, "s": 2329, "text": null }, { "code": null, "e": 2931, "s": 2919, "text": " Output: " }, { "code": null, "e": 2944, "s": 2931, "text": "Button added" }, { "code": null, "e": 2970, "s": 2944, "text": "After clicking “Click me”" }, { "code": null, "e": 3344, "s": 2972, "text": "6. Using the Entry() class we will create a text box for user input. To display the user input text, we’ll make changes to the function clicked(). We can get the user entered text using the get() function. When the Button after entering of the text, a default text concatenated with the user text. Also change button grid location to column 2 as Entry() will be column 1." }, { "code": null, "e": 3353, "s": 3344, "text": "Example:" }, { "code": null, "e": 3361, "s": 3353, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")# Set geometry(widthxheight)root.geometry('350x200') # adding a label to the root windowlbl = Label(root, text = \"Are you a Geek?\")lbl.grid() # adding Entry Fieldtxt = Entry(root, width=10)txt.grid(column =1, row =0) # function to display user text when# button is clickeddef clicked(): res = \"You wrote\" + txt.get() lbl.configure(text = res) # button widget with red color text insidebtn = Button(root, text = \"Click me\" , fg = \"red\", command=clicked)# Set Button Gridbtn.grid(column=2, row=0) # Execute Tkinterroot.mainloop()", "e": 4048, "s": 3361, "text": null }, { "code": null, "e": 4058, "s": 4048, "text": " Output: " }, { "code": null, "e": 4091, "s": 4060, "text": "Entry Widget at column 2 row 0" }, { "code": null, "e": 4120, "s": 4091, "text": "Displaying user input text. " }, { "code": null, "e": 4330, "s": 4122, "text": "7. To add a menu bar, you can use Menu class. First, we create a menu, then we add our first label, and finally, we assign the menu to our window. We can add menu items under any menu by using add_cascade()." }, { "code": null, "e": 4339, "s": 4330, "text": "Example:" }, { "code": null, "e": 4347, "s": 4339, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # create root windowroot = Tk() # root window title and dimensionroot.title(\"Welcome to GeekForGeeks\")# Set geometry(widthxheight)root.geometry('350x200') # adding menu bar in root window# new item in menu bar labelled as 'New'# adding more items in the menu barmenu = Menu(root)item = Menu(menu)item.add_command(label='New')menu.add_cascade(label='File', menu=item)root.config(menu=menu) # adding a label to the root windowlbl = Label(root, text = \"Are you a Geek?\")lbl.grid() # adding Entry Fieldtxt = Entry(root, width=10)txt.grid(column =1, row =0) # function to display user text when# button is clickeddef clicked(): res = \"You wrote\" + txt.get() lbl.configure(text = res) # button widget with red color text insidebtn = Button(root, text = \"Click me\" , fg = \"red\", command=clicked)# Set Button Gridbtn.grid(column=2, row=0) # Execute Tkinterroot.mainloop()", "e": 5268, "s": 4347, "text": null }, { "code": null, "e": 5281, "s": 5268, "text": " Output : " }, { "code": null, "e": 5290, "s": 5281, "text": "Menu bar" }, { "code": null, "e": 5427, "s": 5292, "text": "This simple GUI covers the basics of Tkinter package. Similarly, you can add more widgets and change their configurations as desired. " }, { "code": null, "e": 5633, "s": 5431, "text": "Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called Widgets. The list of commonly used Widgets are mentioned below –" }, { "code": null, "e": 5908, "s": 5637, "text": "All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place. Their description is mentioned below –" }, { "code": null, "e": 5919, "s": 5910, "text": "abhigoya" }, { "code": null, "e": 5931, "s": 5919, "text": "anikakapoor" }, { "code": null, "e": 5941, "s": 5931, "text": "kalrap615" }, { "code": null, "e": 5956, "s": 5941, "text": "Python-tkinter" }, { "code": null, "e": 5963, "s": 5956, "text": "Python" } ]
SQL Query to Display All the Existing Constraints on a Table
30 Dec, 2021 In SQL, we sometimes need to display all the currently existing constraints on a table. The whole process for doing the same is demonstrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table STUDENT_INFO inside the database GeeksForGeeks. This table has 3 columns namely ROLL_NO, STUDENT_NAME, and BRANCH containing the roll number, name, and branch of various students. Query: CREATE TABLE STUDENT_INFO( ROLL_NO INT, STUDENT_NAME VARCHAR(10), BRANCH VARCHAR(5) ); Output: Step 4: Display the current constraints applied on the table STUDENT_INFO. We use INFORMATION_SCHEMA.TABLE_CONSTRAINTS to display the constraints. Here, we display the name(CONSTRAINT_NAME) and the type of the constraint(CONSTRAINT_TYPE) for all existing constraints. Syntax: SELECT INFORMATION FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='TABLE_NAME'; Query: SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='STUDENT_INFO'; Note – Since our table has no constraints currently, hence no rows are displayed. Output: Step 5: Alter the ROLL_NO column using ALTER clause table to set it to NOT NULL. We do this because it is a prerequisite for setting the ROLL_NO as a PRIMARY KEY(done in the next step). Query: ALTER TABLE STUDENT_INFO ALTER COLUMN ROLL_NO INT NOT NULL; Output: Step 6: Add a PRIMARY KEY constraint named C1 to the ROLL_NO column using ALTER clause. Query: ALTER TABLE STUDENT_INFO ADD CONSTRAINT C1 PRIMARY KEY (ROLL_NO); Output: Step 7: Display the current constraints applied on the table STUDENT_INFO. Query: SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='STUDENT_INFO'; Note: Since our table has only 1 constraint i.e. the PRIMARY KEY constraint currently, hence only 1 row is displayed. Output: Step 8: Add a CHECK constraint named BRANCH_CHECK to the BRANCH column using ALTER clause. Query: ALTER TABLE STUDENT_INFO ADD CONSTRAINT BRANCH_CHECK CHECK (BRANCH IN('CSE','ECE','CE','ME','ELE')); Output: Step 9: Display the current constraints applied on the table STUDENT_INFO. Query: SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='STUDENT_INFO'; Note: Since our table has 2 constraints i.e. the PRIMARY KEY constraint and the CHECK constraint currently, hence 2 rows are displayed. Output: Step 10: Add a UNIQUE constraint named UNIQ to the STUDENT_NAME column using ALTER clause. Query: ALTER TABLE STUDENT_INFO ADD CONSTRAINT UNIQ UNIQUE(STUDENT_NAME); Output: Step 11: Display the current constraints applied on the table STUDENT_INFO. Query: SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='STUDENT_INFO'; Note: Since our table has 3 constraints i.e. the PRIMARY KEY constraint, the CHECK constraint, and the UNIQUE constraint currently, hence 3 rows are displayed. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2021" }, { "code": null, "e": 253, "s": 28, "text": "In SQL, we sometimes need to display all the currently existing constraints on a table. The whole process for doing the same is demonstrated below. For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 353, "s": 253, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 360, "s": 353, "text": "Query:" }, { "code": null, "e": 390, "s": 360, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 398, "s": 390, "text": "Output:" }, { "code": null, "e": 470, "s": 398, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 477, "s": 470, "text": "Query:" }, { "code": null, "e": 495, "s": 477, "text": "USE GeeksForGeeks" }, { "code": null, "e": 503, "s": 495, "text": "Output:" }, { "code": null, "e": 706, "s": 503, "text": "Step 3: Create a table STUDENT_INFO inside the database GeeksForGeeks. This table has 3 columns namely ROLL_NO, STUDENT_NAME, and BRANCH containing the roll number, name, and branch of various students." }, { "code": null, "e": 713, "s": 706, "text": "Query:" }, { "code": null, "e": 800, "s": 713, "text": "CREATE TABLE STUDENT_INFO(\nROLL_NO INT,\nSTUDENT_NAME VARCHAR(10),\nBRANCH VARCHAR(5)\n);" }, { "code": null, "e": 808, "s": 800, "text": "Output:" }, { "code": null, "e": 1076, "s": 808, "text": "Step 4: Display the current constraints applied on the table STUDENT_INFO. We use INFORMATION_SCHEMA.TABLE_CONSTRAINTS to display the constraints. Here, we display the name(CONSTRAINT_NAME) and the type of the constraint(CONSTRAINT_TYPE) for all existing constraints." }, { "code": null, "e": 1084, "s": 1076, "text": "Syntax:" }, { "code": null, "e": 1176, "s": 1084, "text": "SELECT INFORMATION\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE TABLE_NAME='TABLE_NAME';" }, { "code": null, "e": 1183, "s": 1176, "text": "Query:" }, { "code": null, "e": 1298, "s": 1183, "text": "SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE TABLE_NAME='STUDENT_INFO';" }, { "code": null, "e": 1380, "s": 1298, "text": "Note – Since our table has no constraints currently, hence no rows are displayed." }, { "code": null, "e": 1388, "s": 1380, "text": "Output:" }, { "code": null, "e": 1574, "s": 1388, "text": "Step 5: Alter the ROLL_NO column using ALTER clause table to set it to NOT NULL. We do this because it is a prerequisite for setting the ROLL_NO as a PRIMARY KEY(done in the next step)." }, { "code": null, "e": 1581, "s": 1574, "text": "Query:" }, { "code": null, "e": 1642, "s": 1581, "text": "ALTER TABLE STUDENT_INFO ALTER \nCOLUMN ROLL_NO INT NOT NULL;" }, { "code": null, "e": 1650, "s": 1642, "text": "Output:" }, { "code": null, "e": 1738, "s": 1650, "text": "Step 6: Add a PRIMARY KEY constraint named C1 to the ROLL_NO column using ALTER clause." }, { "code": null, "e": 1745, "s": 1738, "text": "Query:" }, { "code": null, "e": 1812, "s": 1745, "text": "ALTER TABLE STUDENT_INFO ADD CONSTRAINT \nC1 PRIMARY KEY (ROLL_NO);" }, { "code": null, "e": 1820, "s": 1812, "text": "Output:" }, { "code": null, "e": 1895, "s": 1820, "text": "Step 7: Display the current constraints applied on the table STUDENT_INFO." }, { "code": null, "e": 1902, "s": 1895, "text": "Query:" }, { "code": null, "e": 2017, "s": 1902, "text": "SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE TABLE_NAME='STUDENT_INFO';" }, { "code": null, "e": 2135, "s": 2017, "text": "Note: Since our table has only 1 constraint i.e. the PRIMARY KEY constraint currently, hence only 1 row is displayed." }, { "code": null, "e": 2143, "s": 2135, "text": "Output:" }, { "code": null, "e": 2234, "s": 2143, "text": "Step 8: Add a CHECK constraint named BRANCH_CHECK to the BRANCH column using ALTER clause." }, { "code": null, "e": 2241, "s": 2234, "text": "Query:" }, { "code": null, "e": 2342, "s": 2241, "text": "ALTER TABLE STUDENT_INFO ADD CONSTRAINT BRANCH_CHECK\nCHECK (BRANCH IN('CSE','ECE','CE','ME','ELE'));" }, { "code": null, "e": 2350, "s": 2342, "text": "Output:" }, { "code": null, "e": 2425, "s": 2350, "text": "Step 9: Display the current constraints applied on the table STUDENT_INFO." }, { "code": null, "e": 2432, "s": 2425, "text": "Query:" }, { "code": null, "e": 2547, "s": 2432, "text": "SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE TABLE_NAME='STUDENT_INFO';" }, { "code": null, "e": 2683, "s": 2547, "text": "Note: Since our table has 2 constraints i.e. the PRIMARY KEY constraint and the CHECK constraint currently, hence 2 rows are displayed." }, { "code": null, "e": 2691, "s": 2683, "text": "Output:" }, { "code": null, "e": 2782, "s": 2691, "text": "Step 10: Add a UNIQUE constraint named UNIQ to the STUDENT_NAME column using ALTER clause." }, { "code": null, "e": 2789, "s": 2782, "text": "Query:" }, { "code": null, "e": 2857, "s": 2789, "text": "ALTER TABLE STUDENT_INFO ADD CONSTRAINT \nUNIQ UNIQUE(STUDENT_NAME);" }, { "code": null, "e": 2865, "s": 2857, "text": "Output:" }, { "code": null, "e": 2941, "s": 2865, "text": "Step 11: Display the current constraints applied on the table STUDENT_INFO." }, { "code": null, "e": 2948, "s": 2941, "text": "Query:" }, { "code": null, "e": 3063, "s": 2948, "text": "SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE TABLE_NAME='STUDENT_INFO';" }, { "code": null, "e": 3223, "s": 3063, "text": "Note: Since our table has 3 constraints i.e. the PRIMARY KEY constraint, the CHECK constraint, and the UNIQUE constraint currently, hence 3 rows are displayed." }, { "code": null, "e": 3231, "s": 3223, "text": "Output:" }, { "code": null, "e": 3238, "s": 3231, "text": "Picked" }, { "code": null, "e": 3248, "s": 3238, "text": "SQL-Query" }, { "code": null, "e": 3259, "s": 3248, "text": "SQL-Server" }, { "code": null, "e": 3263, "s": 3259, "text": "SQL" }, { "code": null, "e": 3267, "s": 3263, "text": "SQL" } ]
Number with maximum number of prime factors
22 Jun, 2022 Given an integer N. The task is to find a number that is smaller than or equal to N and has maximum prime factors. In case there are two or more numbers with the same maximum number of prime factors, find the smallest of all.Examples: Input : N = 10 Output : 6 Number of prime factor of: 1 : 0 2 : 1 3 : 1 4 : 1 5 : 1 6 : 2 7 : 1 8 : 1 9 : 1 10 : 2 6 and 10 have maximum (2) prime factor but 6 is smaller. Input : N = 40 Output : 30 Method 1 (brute force): For each integer from 1 to N, find the number of prime factors of each integer and find the smallest number having a maximum number of prime factors.Method 2 (Better Approach): Use sieve method to count a number of prime factors of each number less than N. And find the minimum number having maximum count.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find integer having maximum number// of prime factor in first N natural numbers.#include<bits/stdc++.h> using namespace std; // Return smallest number having maximum// prime factors.int maxPrimefactorNum(int N){ int arr[N + 5]; memset(arr, 0, sizeof(arr)); // Sieve of eratosthenes method to count // number of prime factors. for (int i = 2; i*i <= N; i++) { if (!arr[i]) for (int j = 2*i; j <= N; j+=i) arr[j]++; arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum number // of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint;} // Driven Programint main(){ int N = 40; cout << maxPrimefactorNum(N) << endl; return 0;} // Java program to find integer having maximum number// of prime factor in first N natural numbers.import java.util.Arrays;public class GFG { // Return smallest number having maximum// prime factors. static int maxPrimefactorNum(int N) { int arr[] = new int[N + 5]; Arrays.fill(arr, 0); // Sieve of eratosthenes method to count // number of prime factors. for (int i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (int j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum number // of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint; }// Driver program public static void main(String[] args) { int N = 40; System.out.println(maxPrimefactorNum(N)); }} # Python 3 program to find integer having# maximum number of prime factor in first# N natural numbers.from math import sqrt # Return smallest number having maximum# prime factors.def maxPrimefactorNum(N): arr = [0 for i in range(N + 5)] # Sieve of eratosthenes method to # count number of prime factors. for i in range(2, int(sqrt(N)) + 1, 1): if (arr[i] == 0): for j in range(2 * i, N + 1, i): arr[j] += 1 arr[i] = 1 maxval = 0 maxint = 1 # Finding number having maximum # number of prime factor. for i in range(1, N + 1, 1): if (arr[i] > maxval): maxval = arr[i] maxint = i return maxint # Driver Codeif __name__ == '__main__': N = 40 print(maxPrimefactorNum(N)) # This code is contributed by# Sahil_Shelangia // C# program to find integer having// maximum number of prime factor in// first N natural numbers.using System; class GFG{ // Return smallest number having// prime factors.static int maxPrimefactorNum(int N){ int []arr = new int[N + 5]; // Sieve of eratosthenes method to // count number of prime factors. for (int i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (int j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum // number of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint;} // Driver Codepublic static void Main(){ int N = 40; Console.WriteLine(maxPrimefactorNum(N));}} // This code is contributed// by 29AjayKumar <?php// PHP program to find integer having// maximum number of prime factor in// first N natural numbers. // Return smallest number having// maximum prime factors.function maxPrimefactorNum($N){ $arr[$N + 5] = array(); $arr = array_fill(0, $N + 1, NULL); // Sieve of eratosthenes method to count // number of prime factors. for ($i = 2; ($i * $i) <= $N; $i++) { if (!$arr[$i]) for ($j = 2 * $i; $j <= $N; $j += $i) $arr[$j]++; $arr[$i] = 1; } $maxval = 0; $maxint = 1; // Finding number having maximum // number of prime factor. for ($i = 1; $i <= $N; $i++) { if ($arr[$i] > $maxval) { $maxval = $arr[$i]; $maxint = $i; } } return $maxint;} // Driver Code$N = 40;echo maxPrimefactorNum($N), "\n"; // This code is contributed by ajit?> <script>// javascript program to find integer having maximum number// of prime factor in first N natural numbers. // Return smallest number having maximum// prime factors.function maxPrimefactorNum(N) { var arr = Array.from({length: N + 5}, (_, i) => 0); // Sieve of eratosthenes method to count // number of prime factors. for (i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } var maxval = 0, maxvar = 1; // Finding number having maximum number // of prime factor. for (i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxvar = i; } } return maxvar;}// Driver programvar N = 40;document.write(maxPrimefactorNum(N)); // This code contributed by Princi Singh</script> Output: 30 Time comlexity: O(n) Auxiliary space: O(1) Method 3 (efficient approach): Generate all prime numbers before N using Sieve. Now, multiply consecutive prime numbers (starting from the first prime number) one after another until the product is less than N.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find integer having maximum number// of prime factor in first N natural numbers#include<bits/stdc++.h> using namespace std; // Return smallest number having maximum prime factors.int maxPrimefactorNum(int N){ bool arr[N + 5]; memset(arr, true, sizeof(arr)); // Sieve of eratosthenes for (int i = 3; i*i <= N; i += 2) { if (arr[i]) for (int j = i*i; j <= N; j+=i) arr[j] = false; } // Storing prime numbers. vector<int> prime; prime.push_back(2); for(int i = 3; i <= N; i += 2) if(arr[i]) prime.push_back(i); // Generating number having maximum prime factors. int i = 0, ans = 1; while (ans*prime[i] <= N && i < prime.size()) { ans *= prime[i]; i++; } return ans;} // Driven Programint main(){ int N = 40; cout << maxPrimefactorNum(N) << endl; return 0;} // Java program to find integer having maximum number// of prime factor in first N natural numbersimport java.util.Vector; public class GFG { // Return smallest number having maximum prime factors. static int maxPrimefactorNum(int N) { //default value of boolean is false boolean arr[] = new boolean[N + 5]; // Sieve of eratosthenes for (int i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (int j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. Vector<Integer> prime = new Vector<>(); prime.add(prime.size(), 2); for (int i = 3; i <= N; i += 2) { if (!arr[i]) { prime.add(prime.size(), i); } } // Generating number having maximum prime factors. int i = 0, ans = 1; while (ans * prime.get(i) <= N && i < prime.size()) { ans *= prime.get(i); i++; } return ans; }// Driver program public static void main(String[] args) { int N = 40; System.out.println(maxPrimefactorNum(N)); }} # Python3 program to find integer having# maximum number of prime factor in first# N natural numbers # Return smallest number having# maximum prime factors.def maxPrimefactorNum(N): arr = [True] * (N + 5); # Sieve of eratosthenes i = 3; while (i * i <= N): if (arr[i]): for j in range(i * i, N + 1, i): arr[j] = False; i += 2; # Storing prime numbers. prime = []; prime.append(2); for i in range(3, N + 1, 2): if(arr[i]): prime.append(i); # Generating number having maximum # prime factors. i = 0; ans = 1; while (ans * prime[i] <= N and i < len(prime)): ans *= prime[i]; i += 1; return ans; # Driver CodeN = 40;print(maxPrimefactorNum(N)); # This code is contributed by mits // C# program to find integer having maximum number// of prime factor in first N natural numbersusing System;using System.Collections; class GFG { // Return smallest number having maximum prime factors. static int maxPrimefactorNum(int N) { //default value of boolean is false bool []arr = new bool[N + 5]; int i ; // Sieve of eratosthenes for (i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (int j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. ArrayList prime = new ArrayList(); prime.Add(2); for (i = 3; i <= N; i += 2) { if (!arr[i]) { prime.Add(i); } } // Generating number having // maximum prime factors. int ans = 1; i = 0; while (ans * (int)prime[i] <= N && i < prime.Count) { ans *= (int)prime[i]; i++; } return ans; } // Driver code public static void Main() { int N = 40; Console.Write(maxPrimefactorNum(N)); }} // This code is contributed by Rajput-Ji <?php// PHP program to find integer having maximum number// of prime factor in first N natural numbers // Return smallest number having// maximum prime factors.function maxPrimefactorNum($N){ $arr = array_fill(0, $N + 5, true); // Sieve of eratosthenes for ($i = 3; $i * $i <= $N; $i += 2) { if ($arr[$i]) for ($j = $i * $i; $j <= $N; $j += $i) $arr[$j] = false; } // Storing prime numbers. $prime = array(); array_push($prime, 2); for($i = 3; $i <= $N; $i += 2) if($arr[$i]) array_push($prime, $i); // Generating number having maximum // prime factors. $i = 0; $ans = 1; while ($ans * $prime[$i] <= $N && $i < count($prime)) { $ans *= $prime[$i]; $i++; } return $ans;} // Driver Code$N = 40;print(maxPrimefactorNum($N)); // This code is contributed by mits?> <script> // Javascript program to find // integer having maximum number // of prime factor in first // N natural numbers // Return smallest number having // maximum prime factors. function maxPrimefactorNum(N) { // default value of boolean is false let arr = new Array(N + 5); arr.fill(false); let i ; // Sieve of eratosthenes for (i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (let j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. let prime = []; prime.push(2); for (i = 3; i <= N; i += 2) { if (!arr[i]) { prime.push(i); } } // Generating number having // maximum prime factors. let ans = 1; i = 0; while (ans * prime[i] <= N && i < prime.length) { ans *= prime[i]; i++; } return ans; } let N = 40; document.write(maxPrimefactorNum(N)); </script> Output: 30 Time complexity: O(nsqrtn) Auxiliary space: O(n) This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rupesh nitnaware 29AjayKumar jit_t sahilshelangia Rajput-Ji Mithun Kumar princi singh divyeshrabadiya07 shaheeneallamaiqbal prime-factor sieve Mathematical Mathematical sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 289, "s": 52, "text": "Given an integer N. The task is to find a number that is smaller than or equal to N and has maximum prime factors. In case there are two or more numbers with the same maximum number of prime factors, find the smallest of all.Examples: " }, { "code": null, "e": 488, "s": 289, "text": "Input : N = 10\nOutput : 6\nNumber of prime factor of:\n1 : 0\n2 : 1\n3 : 1\n4 : 1\n5 : 1\n6 : 2\n7 : 1\n8 : 1\n9 : 1\n10 : 2\n6 and 10 have maximum (2) prime factor\nbut 6 is smaller.\n\nInput : N = 40\nOutput : 30" }, { "code": null, "e": 868, "s": 490, "text": "Method 1 (brute force): For each integer from 1 to N, find the number of prime factors of each integer and find the smallest number having a maximum number of prime factors.Method 2 (Better Approach): Use sieve method to count a number of prime factors of each number less than N. And find the minimum number having maximum count.Below is the implementation of this approach: " }, { "code": null, "e": 872, "s": 868, "text": "C++" }, { "code": null, "e": 877, "s": 872, "text": "Java" }, { "code": null, "e": 885, "s": 877, "text": "Python3" }, { "code": null, "e": 888, "s": 885, "text": "C#" }, { "code": null, "e": 892, "s": 888, "text": "PHP" }, { "code": null, "e": 903, "s": 892, "text": "Javascript" }, { "code": "// C++ program to find integer having maximum number// of prime factor in first N natural numbers.#include<bits/stdc++.h> using namespace std; // Return smallest number having maximum// prime factors.int maxPrimefactorNum(int N){ int arr[N + 5]; memset(arr, 0, sizeof(arr)); // Sieve of eratosthenes method to count // number of prime factors. for (int i = 2; i*i <= N; i++) { if (!arr[i]) for (int j = 2*i; j <= N; j+=i) arr[j]++; arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum number // of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint;} // Driven Programint main(){ int N = 40; cout << maxPrimefactorNum(N) << endl; return 0;}", "e": 1769, "s": 903, "text": null }, { "code": "// Java program to find integer having maximum number// of prime factor in first N natural numbers.import java.util.Arrays;public class GFG { // Return smallest number having maximum// prime factors. static int maxPrimefactorNum(int N) { int arr[] = new int[N + 5]; Arrays.fill(arr, 0); // Sieve of eratosthenes method to count // number of prime factors. for (int i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (int j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum number // of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint; }// Driver program public static void main(String[] args) { int N = 40; System.out.println(maxPrimefactorNum(N)); }}", "e": 2810, "s": 1769, "text": null }, { "code": "# Python 3 program to find integer having# maximum number of prime factor in first# N natural numbers.from math import sqrt # Return smallest number having maximum# prime factors.def maxPrimefactorNum(N): arr = [0 for i in range(N + 5)] # Sieve of eratosthenes method to # count number of prime factors. for i in range(2, int(sqrt(N)) + 1, 1): if (arr[i] == 0): for j in range(2 * i, N + 1, i): arr[j] += 1 arr[i] = 1 maxval = 0 maxint = 1 # Finding number having maximum # number of prime factor. for i in range(1, N + 1, 1): if (arr[i] > maxval): maxval = arr[i] maxint = i return maxint # Driver Codeif __name__ == '__main__': N = 40 print(maxPrimefactorNum(N)) # This code is contributed by# Sahil_Shelangia", "e": 3636, "s": 2810, "text": null }, { "code": "// C# program to find integer having// maximum number of prime factor in// first N natural numbers.using System; class GFG{ // Return smallest number having// prime factors.static int maxPrimefactorNum(int N){ int []arr = new int[N + 5]; // Sieve of eratosthenes method to // count number of prime factors. for (int i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (int j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } int maxval = 0, maxint = 1; // Finding number having maximum // number of prime factor. for (int i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxint = i; } } return maxint;} // Driver Codepublic static void Main(){ int N = 40; Console.WriteLine(maxPrimefactorNum(N));}} // This code is contributed// by 29AjayKumar", "e": 4568, "s": 3636, "text": null }, { "code": "<?php// PHP program to find integer having// maximum number of prime factor in// first N natural numbers. // Return smallest number having// maximum prime factors.function maxPrimefactorNum($N){ $arr[$N + 5] = array(); $arr = array_fill(0, $N + 1, NULL); // Sieve of eratosthenes method to count // number of prime factors. for ($i = 2; ($i * $i) <= $N; $i++) { if (!$arr[$i]) for ($j = 2 * $i; $j <= $N; $j += $i) $arr[$j]++; $arr[$i] = 1; } $maxval = 0; $maxint = 1; // Finding number having maximum // number of prime factor. for ($i = 1; $i <= $N; $i++) { if ($arr[$i] > $maxval) { $maxval = $arr[$i]; $maxint = $i; } } return $maxint;} // Driver Code$N = 40;echo maxPrimefactorNum($N), \"\\n\"; // This code is contributed by ajit?>", "e": 5440, "s": 4568, "text": null }, { "code": "<script>// javascript program to find integer having maximum number// of prime factor in first N natural numbers. // Return smallest number having maximum// prime factors.function maxPrimefactorNum(N) { var arr = Array.from({length: N + 5}, (_, i) => 0); // Sieve of eratosthenes method to count // number of prime factors. for (i = 2; i * i <= N; i++) { if (arr[i] == 0) { for (j = 2 * i; j <= N; j += i) { arr[j]++; } } arr[i] = 1; } var maxval = 0, maxvar = 1; // Finding number having maximum number // of prime factor. for (i = 1; i <= N; i++) { if (arr[i] > maxval) { maxval = arr[i]; maxvar = i; } } return maxvar;}// Driver programvar N = 40;document.write(maxPrimefactorNum(N)); // This code contributed by Princi Singh</script>", "e": 6315, "s": 5440, "text": null }, { "code": null, "e": 6325, "s": 6315, "text": "Output: " }, { "code": null, "e": 6328, "s": 6325, "text": "30" }, { "code": null, "e": 6349, "s": 6328, "text": "Time comlexity: O(n)" }, { "code": null, "e": 6371, "s": 6349, "text": "Auxiliary space: O(1)" }, { "code": null, "e": 6629, "s": 6371, "text": "Method 3 (efficient approach): Generate all prime numbers before N using Sieve. Now, multiply consecutive prime numbers (starting from the first prime number) one after another until the product is less than N.Below is the implementation of this approach: " }, { "code": null, "e": 6633, "s": 6629, "text": "C++" }, { "code": null, "e": 6638, "s": 6633, "text": "Java" }, { "code": null, "e": 6646, "s": 6638, "text": "Python3" }, { "code": null, "e": 6649, "s": 6646, "text": "C#" }, { "code": null, "e": 6653, "s": 6649, "text": "PHP" }, { "code": null, "e": 6664, "s": 6653, "text": "Javascript" }, { "code": "// C++ program to find integer having maximum number// of prime factor in first N natural numbers#include<bits/stdc++.h> using namespace std; // Return smallest number having maximum prime factors.int maxPrimefactorNum(int N){ bool arr[N + 5]; memset(arr, true, sizeof(arr)); // Sieve of eratosthenes for (int i = 3; i*i <= N; i += 2) { if (arr[i]) for (int j = i*i; j <= N; j+=i) arr[j] = false; } // Storing prime numbers. vector<int> prime; prime.push_back(2); for(int i = 3; i <= N; i += 2) if(arr[i]) prime.push_back(i); // Generating number having maximum prime factors. int i = 0, ans = 1; while (ans*prime[i] <= N && i < prime.size()) { ans *= prime[i]; i++; } return ans;} // Driven Programint main(){ int N = 40; cout << maxPrimefactorNum(N) << endl; return 0;}", "e": 7563, "s": 6664, "text": null }, { "code": "// Java program to find integer having maximum number// of prime factor in first N natural numbersimport java.util.Vector; public class GFG { // Return smallest number having maximum prime factors. static int maxPrimefactorNum(int N) { //default value of boolean is false boolean arr[] = new boolean[N + 5]; // Sieve of eratosthenes for (int i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (int j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. Vector<Integer> prime = new Vector<>(); prime.add(prime.size(), 2); for (int i = 3; i <= N; i += 2) { if (!arr[i]) { prime.add(prime.size(), i); } } // Generating number having maximum prime factors. int i = 0, ans = 1; while (ans * prime.get(i) <= N && i < prime.size()) { ans *= prime.get(i); i++; } return ans; }// Driver program public static void main(String[] args) { int N = 40; System.out.println(maxPrimefactorNum(N)); }}", "e": 8731, "s": 7563, "text": null }, { "code": "# Python3 program to find integer having# maximum number of prime factor in first# N natural numbers # Return smallest number having# maximum prime factors.def maxPrimefactorNum(N): arr = [True] * (N + 5); # Sieve of eratosthenes i = 3; while (i * i <= N): if (arr[i]): for j in range(i * i, N + 1, i): arr[j] = False; i += 2; # Storing prime numbers. prime = []; prime.append(2); for i in range(3, N + 1, 2): if(arr[i]): prime.append(i); # Generating number having maximum # prime factors. i = 0; ans = 1; while (ans * prime[i] <= N and i < len(prime)): ans *= prime[i]; i += 1; return ans; # Driver CodeN = 40;print(maxPrimefactorNum(N)); # This code is contributed by mits", "e": 9546, "s": 8731, "text": null }, { "code": "// C# program to find integer having maximum number// of prime factor in first N natural numbersusing System;using System.Collections; class GFG { // Return smallest number having maximum prime factors. static int maxPrimefactorNum(int N) { //default value of boolean is false bool []arr = new bool[N + 5]; int i ; // Sieve of eratosthenes for (i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (int j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. ArrayList prime = new ArrayList(); prime.Add(2); for (i = 3; i <= N; i += 2) { if (!arr[i]) { prime.Add(i); } } // Generating number having // maximum prime factors. int ans = 1; i = 0; while (ans * (int)prime[i] <= N && i < prime.Count) { ans *= (int)prime[i]; i++; } return ans; } // Driver code public static void Main() { int N = 40; Console.Write(maxPrimefactorNum(N)); }} // This code is contributed by Rajput-Ji", "e": 10805, "s": 9546, "text": null }, { "code": "<?php// PHP program to find integer having maximum number// of prime factor in first N natural numbers // Return smallest number having// maximum prime factors.function maxPrimefactorNum($N){ $arr = array_fill(0, $N + 5, true); // Sieve of eratosthenes for ($i = 3; $i * $i <= $N; $i += 2) { if ($arr[$i]) for ($j = $i * $i; $j <= $N; $j += $i) $arr[$j] = false; } // Storing prime numbers. $prime = array(); array_push($prime, 2); for($i = 3; $i <= $N; $i += 2) if($arr[$i]) array_push($prime, $i); // Generating number having maximum // prime factors. $i = 0; $ans = 1; while ($ans * $prime[$i] <= $N && $i < count($prime)) { $ans *= $prime[$i]; $i++; } return $ans;} // Driver Code$N = 40;print(maxPrimefactorNum($N)); // This code is contributed by mits?>", "e": 11703, "s": 10805, "text": null }, { "code": "<script> // Javascript program to find // integer having maximum number // of prime factor in first // N natural numbers // Return smallest number having // maximum prime factors. function maxPrimefactorNum(N) { // default value of boolean is false let arr = new Array(N + 5); arr.fill(false); let i ; // Sieve of eratosthenes for (i = 3; i * i <= N; i += 2) { if (!arr[i]) { for (let j = i * i; j <= N; j += i) { arr[j] = true; } } } // Storing prime numbers. let prime = []; prime.push(2); for (i = 3; i <= N; i += 2) { if (!arr[i]) { prime.push(i); } } // Generating number having // maximum prime factors. let ans = 1; i = 0; while (ans * prime[i] <= N && i < prime.length) { ans *= prime[i]; i++; } return ans; } let N = 40; document.write(maxPrimefactorNum(N)); </script>", "e": 12868, "s": 11703, "text": null }, { "code": null, "e": 12877, "s": 12868, "text": "Output: " }, { "code": null, "e": 12880, "s": 12877, "text": "30" }, { "code": null, "e": 12907, "s": 12880, "text": "Time complexity: O(nsqrtn)" }, { "code": null, "e": 12929, "s": 12907, "text": "Auxiliary space: O(n)" }, { "code": null, "e": 13350, "s": 12929, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13367, "s": 13350, "text": "rupesh nitnaware" }, { "code": null, "e": 13379, "s": 13367, "text": "29AjayKumar" }, { "code": null, "e": 13385, "s": 13379, "text": "jit_t" }, { "code": null, "e": 13400, "s": 13385, "text": "sahilshelangia" }, { "code": null, "e": 13410, "s": 13400, "text": "Rajput-Ji" }, { "code": null, "e": 13423, "s": 13410, "text": "Mithun Kumar" }, { "code": null, "e": 13436, "s": 13423, "text": "princi singh" }, { "code": null, "e": 13454, "s": 13436, "text": "divyeshrabadiya07" }, { "code": null, "e": 13474, "s": 13454, "text": "shaheeneallamaiqbal" }, { "code": null, "e": 13487, "s": 13474, "text": "prime-factor" }, { "code": null, "e": 13493, "s": 13487, "text": "sieve" }, { "code": null, "e": 13506, "s": 13493, "text": "Mathematical" }, { "code": null, "e": 13519, "s": 13506, "text": "Mathematical" }, { "code": null, "e": 13525, "s": 13519, "text": "sieve" } ]
Python PIL | copy() method
25 Jun, 2019 Syntax:Image.copy() Parameters: no arguments Returns:An image object # Importing Image module from PIL packagefrom PIL import Image # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") # copying image to another image objectim2 = im1.copy() # shows the copied imageim2.show() Output: # Importing Image module from PIL packagefrom PIL import Image # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") # copying image to another image objectim2 = im1.copy() # shows the original imageim1.show() Output: python-utility 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": "\n25 Jun, 2019" }, { "code": null, "e": 100, "s": 28, "text": "Syntax:Image.copy()\n\nParameters: no arguments\n\nReturns:An image object\n" }, { "code": "# Importing Image module from PIL packagefrom PIL import Image # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") # copying image to another image objectim2 = im1.copy() # shows the copied imageim2.show()", "e": 336, "s": 100, "text": null }, { "code": null, "e": 344, "s": 336, "text": "Output:" }, { "code": "# Importing Image module from PIL packagefrom PIL import Image # creating a image objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") # copying image to another image objectim2 = im1.copy() # shows the original imageim1.show()", "e": 582, "s": 344, "text": null }, { "code": null, "e": 590, "s": 582, "text": "Output:" }, { "code": null, "e": 605, "s": 590, "text": "python-utility" }, { "code": null, "e": 612, "s": 605, "text": "Python" }, { "code": null, "e": 710, "s": 612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 728, "s": 710, "text": "Python Dictionary" }, { "code": null, "e": 770, "s": 728, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 792, "s": 770, "text": "Enumerate() in Python" }, { "code": null, "e": 827, "s": 792, "text": "Read a file line by line in Python" }, { "code": null, "e": 853, "s": 827, "text": "Python String | replace()" }, { "code": null, "e": 885, "s": 853, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 914, "s": 885, "text": "*args and **kwargs in Python" }, { "code": null, "e": 941, "s": 914, "text": "Python Classes and Objects" }, { "code": null, "e": 971, "s": 941, "text": "Iterate over a list in Python" } ]
Install Apache Spark in a Standalone Mode on Windows
15 Mar, 2021 Apache Spark is a lightning-fast unified analytics engine used for cluster computing for large data sets like BigData and Hadoop with the aim to run programs parallel across multiple nodes. It is a combination of multiple stack libraries such as SQL and Dataframes, GraphX, MLlib, and Spark Streaming. Spark operates in 4 different modes: Standalone Mode: Here all processes run within the same JVM process.Standalone Cluster Mode: In this mode, it uses the Job-Scheduling framework in-built in Spark.Apache Mesos: In this mode, the work nodes run on various machines, but the driver runs only in the master node.Hadoop YARN: In this mode, the drivers run inside the application’s master node and is handled by YARN on the Cluster. Standalone Mode: Here all processes run within the same JVM process. Standalone Cluster Mode: In this mode, it uses the Job-Scheduling framework in-built in Spark. Apache Mesos: In this mode, the work nodes run on various machines, but the driver runs only in the master node. Hadoop YARN: In this mode, the drivers run inside the application’s master node and is handled by YARN on the Cluster. In This article, we will explore Apache Spark installation in a Standalone mode. Apache Spark is developed in Scala programming language and runs on the JVM. Java installation is one of the mandatory things in spark. So let’s start with Java installation. Step 1: Download the Java JDK. Step 2: Open the downloaded Java SE Development Kit and follow along with the instructions for installation. Step 3: Open the environment variable on the laptop by typing it in the windows search bar. To set the JAVA_HOME variable follow the below steps: Click on the User variable Add JAVA_HOME to PATH with value Value: C:\Program Files\Java\jdk1.8.0_261. Click on the System variable Add C:\Program Files\Java\jdk1.8.0_261\bin to PATH variable. Open command prompt and type “java –version”, it will show bellow appear & verify Java installation. For installing Scala on your local machine follow the below steps: Step 1: Download Scala. Step 2: Click on the .exe file and follow along instructions to customize the setup according to your needs. Step 3: Accept the agreement and click the next button. In User Variable Add SCALA_HOME to PATH with value C:\Program Files (x86)\scala. In System Variable Add C:\Program Files (x86)\scala\bin to PATH variable. In the Command prompt use the below command to verify Scala installation: scala Download a pre-built version of the Spark and extract it into the C drive, such as C:\Spark. Then click on the installation file and follow along the instructions to set up Spark. In User variable Add SPARK_HOME to PATH with value C:\spark\spark-2.4.6-bin-hadoop2.7. In System variable Add%SPARK_HOME%\bin to PATH variable. If you wish to operate on Hadoop data follow the below steps to download utility for Hadoop: Step 1: Download the winutils.exe file. Step 2: Copy the file to C:\spark\spark-1.6.1-bin-hadoop2.6\bin. Step 3: Now execute “spark-shell” on cmd to verify spark installation as shown below: Apache-spark Scala Hadoop Java Scala Java Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2021" }, { "code": null, "e": 330, "s": 28, "text": "Apache Spark is a lightning-fast unified analytics engine used for cluster computing for large data sets like BigData and Hadoop with the aim to run programs parallel across multiple nodes. It is a combination of multiple stack libraries such as SQL and Dataframes, GraphX, MLlib, and Spark Streaming." }, { "code": null, "e": 367, "s": 330, "text": "Spark operates in 4 different modes:" }, { "code": null, "e": 760, "s": 367, "text": "Standalone Mode: Here all processes run within the same JVM process.Standalone Cluster Mode: In this mode, it uses the Job-Scheduling framework in-built in Spark.Apache Mesos: In this mode, the work nodes run on various machines, but the driver runs only in the master node.Hadoop YARN: In this mode, the drivers run inside the application’s master node and is handled by YARN on the Cluster." }, { "code": null, "e": 829, "s": 760, "text": "Standalone Mode: Here all processes run within the same JVM process." }, { "code": null, "e": 924, "s": 829, "text": "Standalone Cluster Mode: In this mode, it uses the Job-Scheduling framework in-built in Spark." }, { "code": null, "e": 1037, "s": 924, "text": "Apache Mesos: In this mode, the work nodes run on various machines, but the driver runs only in the master node." }, { "code": null, "e": 1156, "s": 1037, "text": "Hadoop YARN: In this mode, the drivers run inside the application’s master node and is handled by YARN on the Cluster." }, { "code": null, "e": 1413, "s": 1156, "text": "In This article, we will explore Apache Spark installation in a Standalone mode. Apache Spark is developed in Scala programming language and runs on the JVM. Java installation is one of the mandatory things in spark. So let’s start with Java installation. " }, { "code": null, "e": 1444, "s": 1413, "text": "Step 1: Download the Java JDK." }, { "code": null, "e": 1553, "s": 1444, "text": "Step 2: Open the downloaded Java SE Development Kit and follow along with the instructions for installation." }, { "code": null, "e": 1645, "s": 1553, "text": "Step 3: Open the environment variable on the laptop by typing it in the windows search bar." }, { "code": null, "e": 1699, "s": 1645, "text": "To set the JAVA_HOME variable follow the below steps:" }, { "code": null, "e": 1802, "s": 1699, "text": "Click on the User variable Add JAVA_HOME to PATH with value Value: C:\\Program Files\\Java\\jdk1.8.0_261." }, { "code": null, "e": 1892, "s": 1802, "text": "Click on the System variable Add C:\\Program Files\\Java\\jdk1.8.0_261\\bin to PATH variable." }, { "code": null, "e": 1993, "s": 1892, "text": "Open command prompt and type “java –version”, it will show bellow appear & verify Java installation." }, { "code": null, "e": 2060, "s": 1993, "text": "For installing Scala on your local machine follow the below steps:" }, { "code": null, "e": 2085, "s": 2060, "text": "Step 1: Download Scala. " }, { "code": null, "e": 2194, "s": 2085, "text": "Step 2: Click on the .exe file and follow along instructions to customize the setup according to your needs." }, { "code": null, "e": 2251, "s": 2194, "text": "Step 3: Accept the agreement and click the next button. " }, { "code": null, "e": 2333, "s": 2251, "text": "In User Variable Add SCALA_HOME to PATH with value C:\\Program Files (x86)\\scala." }, { "code": null, "e": 2407, "s": 2333, "text": "In System Variable Add C:\\Program Files (x86)\\scala\\bin to PATH variable." }, { "code": null, "e": 2481, "s": 2407, "text": "In the Command prompt use the below command to verify Scala installation:" }, { "code": null, "e": 2487, "s": 2481, "text": "scala" }, { "code": null, "e": 2667, "s": 2487, "text": "Download a pre-built version of the Spark and extract it into the C drive, such as C:\\Spark. Then click on the installation file and follow along the instructions to set up Spark." }, { "code": null, "e": 2754, "s": 2667, "text": "In User variable Add SPARK_HOME to PATH with value C:\\spark\\spark-2.4.6-bin-hadoop2.7." }, { "code": null, "e": 2811, "s": 2754, "text": "In System variable Add%SPARK_HOME%\\bin to PATH variable." }, { "code": null, "e": 2904, "s": 2811, "text": "If you wish to operate on Hadoop data follow the below steps to download utility for Hadoop:" }, { "code": null, "e": 2944, "s": 2904, "text": "Step 1: Download the winutils.exe file." }, { "code": null, "e": 3010, "s": 2944, "text": "Step 2: Copy the file to C:\\spark\\spark-1.6.1-bin-hadoop2.6\\bin." }, { "code": null, "e": 3096, "s": 3010, "text": "Step 3: Now execute “spark-shell” on cmd to verify spark installation as shown below:" }, { "code": null, "e": 3109, "s": 3096, "text": "Apache-spark" }, { "code": null, "e": 3115, "s": 3109, "text": "Scala" }, { "code": null, "e": 3122, "s": 3115, "text": "Hadoop" }, { "code": null, "e": 3127, "s": 3122, "text": "Java" }, { "code": null, "e": 3133, "s": 3127, "text": "Scala" }, { "code": null, "e": 3138, "s": 3133, "text": "Java" }, { "code": null, "e": 3145, "s": 3138, "text": "Hadoop" } ]
Sort the matrix column-wise
04 Jul, 2022 Given a matrix mat[][] of dimensions N * M, the task is to sort each column of a matrix in ascending order and print the updated matrix. Examples: Input: mat[][] = { {1, 6, 10}, {8, 5, 9}, {9, 4, 15}, {7, 3, 60} }Output:1 3 97 4 108 5 159 6 60Explanation:The input matrix is sorted in a column wise manner, 1 < 7 < 8 < 93 < 4 < 5 < 69 < 10 < 15 < 60 Input: arr[][] = { {1, 6}, {8, 4}, {9, 7} }Output:1 48 69 7 Approach: Follow the steps below to solve the problem: Traverse the matrix Find the transpose of the given matrix mat[][]. Store this transpose of mat[][] in a 2D vector, tr[][] Traverse the rows of the matrix tr[][] Sort each row of the matrix using the sort function. Store the transpose of tr[][] in mat[][] Print the matrix, mat[][] Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the transpose// of the matrix mat[]vector<vector<int> > transpose( vector<vector<int> > mat, int row, int col){ // Stores the transpose // of matrix mat[][] vector<vector<int> > tr( col, vector<int>(row)); // Traverse each row of the matrix for (int i = 0; i < row; i++) { // Traverse each column of the matrix for (int j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannervoid RowWiseSort(vector<vector<int> >& B){ // Traverse the row for (int i = 0; i < (int)B.size(); i++) { // Row - Wise Sorting sort(B[i].begin(), B[i].end()); }} // Function to print the matrix// in column wise sorted mannervoid sortCol(vector<vector<int> > mat, int N, int M){ // Function call to find transpose // of the matrix mat[][] vector<vector<int> > B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << mat[i][j] << " "; } cout << '\n'; }} // Driver Codeint main(){ // Input vector<vector<int> > mat = { { 1, 6, 10 }, { 8, 5, 9 }, { 9, 4, 15 }, { 7, 3, 60 } }; int N = mat.size(); int M = mat[0].size(); // Function call to print the matrix // in column wise sorted manner sortCol(mat, N, M); return 0;} // Java program for the above approachimport java.util.*;import java.util.Arrays; class GFG{ // Function to find the transpose// of the matrix mat[]static int[][] transpose(int[][] mat, int row, int col){ // Stores the transpose // of matrix mat[][] int[][] tr = new int[col][row]; // Traverse each row of the matrix for(int i = 0; i < row; i++) { // Traverse each column of the matrix for(int j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannerstatic void RowWiseSort(int[][] B){ // Traverse the row for(int i = 0; i < (int)B.length; i++) { // Row - Wise Sorting Arrays.sort(B[i]); }} // Function to print the matrix// in column wise sorted mannerstatic void sortCol(int[][] mat, int N, int M){ // Function call to find transpose // of the matrix mat[][] int[][] B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { System.out.print(mat[i][j] + " "); } System.out.println(); }} // Driver Codepublic static void main(String[] args){ // Input int[][] mat = { { 1, 6, 10 }, { 8, 5, 9 }, { 9, 4, 15 }, { 7, 3, 60 } }; int N = mat.length; int M = mat[0].length; // Function call to print the matrix // in column wise sorted manner sortCol(mat, N, M);}} // This code is contributed by ukasp # Python3 program for the above approach # Function to find the transpose# of the matrix mat[]def transpose(mat, row, col): # Stores the transpose # of matrix mat[][] tr = [[0 for i in range(row)] for i in range(col)] # Traverse each row of the matrix for i in range(row): # Traverse each column of the matrix for j in range(col): # Transpose matrix elements tr[j][i] = mat[i][j] return tr # Function to sort the given# matrix in row wise mannerdef RowWiseSort(B): # Traverse the row for i in range(len(B)): # Row - Wise Sorting B[i] = sorted(B[i]) return B # Function to print the matrix# in column wise sorted mannerdef sortCol(mat, N, M): # Function call to find transpose # of the matrix mat[][] B = transpose(mat, N, M) # Sorting the matrix row-wise B = RowWiseSort(B) # Calculate transpose of B[][] mat = transpose(B, M, N) # Print the matrix mat[][] for i in range(N): for j in range(M): print(mat[i][j], end = " ") print() # Driver Codeif __name__ == '__main__': # Input mat =[ [1, 6, 10 ], [ 8, 5, 9 ], [ 9, 4, 15 ], [ 7, 3, 60 ] ] N = len(mat) M = len(mat[0]) # Function call to print the matrix # in column wise sorted manner sortCol(mat, N, M) # This code is contributed by mohit kumar 29. <script> // JavaScript program for the above approach // Function to find the transpose// of the matrix mat[]function transpose(mat,row,col){ // Stores the transpose // of matrix mat[][] let tr = new Array(col); for(let i=0;i<col;i++) { tr[i]=new Array(row); } // Traverse each row of the matrix for(let i = 0; i < row; i++) { // Traverse each column of the matrix for(let j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannerfunction RowWiseSort(B){ // Traverse the row for(let i = 0; i < B.length; i++) { // Row - Wise Sorting (B[i]).sort(function(a,b){return a-b;}); }} // Function to print the matrix// in column wise sorted mannerfunction sortCol(mat,n,M){ // Function call to find transpose // of the matrix mat[][] let B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for(let i = 0; i < N; i++) { for(let j = 0; j < M; j++) { document.write(mat[i][j] + " "); } document.write("<br>"); }} // Driver Codelet mat = [[ 1, 6, 10 ], [ 8, 5, 9 ], [ 9, 4, 15 ], [ 7, 3, 60 ] ]; let N = mat.length;let M = mat[0].length; // Function call to print the matrix// in column wise sorted mannersortCol(mat, N, M); // This code is contributed by avanitrachhadiya2155 </script> 1 3 9 7 4 10 8 5 15 9 6 60 Time Complexity: O(N * M)Auxiliary Space: O(N * M) mohit kumar 29 ukasp nidhi_biet avanitrachhadiya2155 simmytarika5 array-rearrange Mathematical Matrix Sorting Mathematical Sorting Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Print a given matrix in spiral form Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 165, "s": 28, "text": "Given a matrix mat[][] of dimensions N * M, the task is to sort each column of a matrix in ascending order and print the updated matrix." }, { "code": null, "e": 175, "s": 165, "text": "Examples:" }, { "code": null, "e": 379, "s": 175, "text": "Input: mat[][] = { {1, 6, 10}, {8, 5, 9}, {9, 4, 15}, {7, 3, 60} }Output:1 3 97 4 108 5 159 6 60Explanation:The input matrix is sorted in a column wise manner, 1 < 7 < 8 < 93 < 4 < 5 < 69 < 10 < 15 < 60" }, { "code": null, "e": 439, "s": 379, "text": "Input: arr[][] = { {1, 6}, {8, 4}, {9, 7} }Output:1 48 69 7" }, { "code": null, "e": 494, "s": 439, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 514, "s": 494, "text": "Traverse the matrix" }, { "code": null, "e": 562, "s": 514, "text": "Find the transpose of the given matrix mat[][]." }, { "code": null, "e": 617, "s": 562, "text": "Store this transpose of mat[][] in a 2D vector, tr[][]" }, { "code": null, "e": 656, "s": 617, "text": "Traverse the rows of the matrix tr[][]" }, { "code": null, "e": 709, "s": 656, "text": "Sort each row of the matrix using the sort function." }, { "code": null, "e": 750, "s": 709, "text": "Store the transpose of tr[][] in mat[][]" }, { "code": null, "e": 776, "s": 750, "text": "Print the matrix, mat[][]" }, { "code": null, "e": 827, "s": 776, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 831, "s": 827, "text": "C++" }, { "code": null, "e": 836, "s": 831, "text": "Java" }, { "code": null, "e": 844, "s": 836, "text": "Python3" }, { "code": null, "e": 855, "s": 844, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the transpose// of the matrix mat[]vector<vector<int> > transpose( vector<vector<int> > mat, int row, int col){ // Stores the transpose // of matrix mat[][] vector<vector<int> > tr( col, vector<int>(row)); // Traverse each row of the matrix for (int i = 0; i < row; i++) { // Traverse each column of the matrix for (int j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannervoid RowWiseSort(vector<vector<int> >& B){ // Traverse the row for (int i = 0; i < (int)B.size(); i++) { // Row - Wise Sorting sort(B[i].begin(), B[i].end()); }} // Function to print the matrix// in column wise sorted mannervoid sortCol(vector<vector<int> > mat, int N, int M){ // Function call to find transpose // of the matrix mat[][] vector<vector<int> > B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << mat[i][j] << \" \"; } cout << '\\n'; }} // Driver Codeint main(){ // Input vector<vector<int> > mat = { { 1, 6, 10 }, { 8, 5, 9 }, { 9, 4, 15 }, { 7, 3, 60 } }; int N = mat.size(); int M = mat[0].size(); // Function call to print the matrix // in column wise sorted manner sortCol(mat, N, M); return 0;}", "e": 2626, "s": 855, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.util.Arrays; class GFG{ // Function to find the transpose// of the matrix mat[]static int[][] transpose(int[][] mat, int row, int col){ // Stores the transpose // of matrix mat[][] int[][] tr = new int[col][row]; // Traverse each row of the matrix for(int i = 0; i < row; i++) { // Traverse each column of the matrix for(int j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannerstatic void RowWiseSort(int[][] B){ // Traverse the row for(int i = 0; i < (int)B.length; i++) { // Row - Wise Sorting Arrays.sort(B[i]); }} // Function to print the matrix// in column wise sorted mannerstatic void sortCol(int[][] mat, int N, int M){ // Function call to find transpose // of the matrix mat[][] int[][] B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { System.out.print(mat[i][j] + \" \"); } System.out.println(); }} // Driver Codepublic static void main(String[] args){ // Input int[][] mat = { { 1, 6, 10 }, { 8, 5, 9 }, { 9, 4, 15 }, { 7, 3, 60 } }; int N = mat.length; int M = mat[0].length; // Function call to print the matrix // in column wise sorted manner sortCol(mat, N, M);}} // This code is contributed by ukasp", "e": 4403, "s": 2626, "text": null }, { "code": "# Python3 program for the above approach # Function to find the transpose# of the matrix mat[]def transpose(mat, row, col): # Stores the transpose # of matrix mat[][] tr = [[0 for i in range(row)] for i in range(col)] # Traverse each row of the matrix for i in range(row): # Traverse each column of the matrix for j in range(col): # Transpose matrix elements tr[j][i] = mat[i][j] return tr # Function to sort the given# matrix in row wise mannerdef RowWiseSort(B): # Traverse the row for i in range(len(B)): # Row - Wise Sorting B[i] = sorted(B[i]) return B # Function to print the matrix# in column wise sorted mannerdef sortCol(mat, N, M): # Function call to find transpose # of the matrix mat[][] B = transpose(mat, N, M) # Sorting the matrix row-wise B = RowWiseSort(B) # Calculate transpose of B[][] mat = transpose(B, M, N) # Print the matrix mat[][] for i in range(N): for j in range(M): print(mat[i][j], end = \" \") print() # Driver Codeif __name__ == '__main__': # Input mat =[ [1, 6, 10 ], [ 8, 5, 9 ], [ 9, 4, 15 ], [ 7, 3, 60 ] ] N = len(mat) M = len(mat[0]) # Function call to print the matrix # in column wise sorted manner sortCol(mat, N, M) # This code is contributed by mohit kumar 29.", "e": 5813, "s": 4403, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the transpose// of the matrix mat[]function transpose(mat,row,col){ // Stores the transpose // of matrix mat[][] let tr = new Array(col); for(let i=0;i<col;i++) { tr[i]=new Array(row); } // Traverse each row of the matrix for(let i = 0; i < row; i++) { // Traverse each column of the matrix for(let j = 0; j < col; j++) { // Transpose matrix elements tr[j][i] = mat[i][j]; } } return tr;} // Function to sort the given// matrix in row wise mannerfunction RowWiseSort(B){ // Traverse the row for(let i = 0; i < B.length; i++) { // Row - Wise Sorting (B[i]).sort(function(a,b){return a-b;}); }} // Function to print the matrix// in column wise sorted mannerfunction sortCol(mat,n,M){ // Function call to find transpose // of the matrix mat[][] let B = transpose(mat, N, M); // Sorting the matrix row-wise RowWiseSort(B); // Calculate transpose of B[][] mat = transpose(B, M, N); // Print the matrix mat[][] for(let i = 0; i < N; i++) { for(let j = 0; j < M; j++) { document.write(mat[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver Codelet mat = [[ 1, 6, 10 ], [ 8, 5, 9 ], [ 9, 4, 15 ], [ 7, 3, 60 ] ]; let N = mat.length;let M = mat[0].length; // Function call to print the matrix// in column wise sorted mannersortCol(mat, N, M); // This code is contributed by avanitrachhadiya2155 </script>", "e": 7483, "s": 5813, "text": null }, { "code": null, "e": 7513, "s": 7483, "text": "1 3 9 \n7 4 10 \n8 5 15 \n9 6 60" }, { "code": null, "e": 7566, "s": 7515, "text": "Time Complexity: O(N * M)Auxiliary Space: O(N * M)" }, { "code": null, "e": 7583, "s": 7568, "text": "mohit kumar 29" }, { "code": null, "e": 7589, "s": 7583, "text": "ukasp" }, { "code": null, "e": 7600, "s": 7589, "text": "nidhi_biet" }, { "code": null, "e": 7621, "s": 7600, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7634, "s": 7621, "text": "simmytarika5" }, { "code": null, "e": 7650, "s": 7634, "text": "array-rearrange" }, { "code": null, "e": 7663, "s": 7650, "text": "Mathematical" }, { "code": null, "e": 7670, "s": 7663, "text": "Matrix" }, { "code": null, "e": 7678, "s": 7670, "text": "Sorting" }, { "code": null, "e": 7691, "s": 7678, "text": "Mathematical" }, { "code": null, "e": 7699, "s": 7691, "text": "Sorting" }, { "code": null, "e": 7706, "s": 7699, "text": "Matrix" }, { "code": null, "e": 7804, "s": 7706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7836, "s": 7804, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7882, "s": 7836, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 7926, "s": 7882, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 7968, "s": 7926, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 8000, "s": 7968, "text": "Check if a number is Palindrome" }, { "code": null, "e": 8036, "s": 8000, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 8071, "s": 8036, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 8115, "s": 8071, "text": "Program to find largest element in an array" }, { "code": null, "e": 8146, "s": 8115, "text": "Rat in a Maze | Backtracking-2" } ]
How to pass or return a structure to/from a Function in C/C++?
16 Dec, 2019 A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to pass structure as an argument to the functions? Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function. In this article, entire structure is passed to the function. This can be done using call by reference as well as call by value method. Examples 1: Using Call By Value Method // C++ program to pass structure as an argument// to the functions using Call By Value Method #include <bits/stdc++.h>using namespace std; struct Distance { int kilometer; int meter;}; // accepts distance as its parametersvoid TotalDistance(Distance d1, Distance d2){ // creating a new instance of the structure Distance d; // assigning value to new instance of structure d.kilometer = d1.kilometer + d2.kilometer + (d1.meter + d2.meter) / 1000; d.meter = (d1.meter + d2.meter) % 1000; cout << "Total distance:"; cout << "kilometer: " << d.kilometer << endl; cout << "meter: " << d.meter << endl;} // Function that initialises the value// and calls TotalDistance functionvoid initializeFunction(){ // creating two instances of Distance Distance Distance1, Distance2; // assigning values to structure elements Distance1.kilometer = 10; Distance1.meter = 455; Distance2.kilometer = 9; Distance2.meter = 745; // calling function with (structure) // distance as parameters TotalDistance(Distance1, Distance2);} // Driver code0int main(){ // Calling function to do required task initializeFunction(); return 0;} Total distance:kilometer: 20 meter: 200 Examples 2: Using Call By Reference Method // C++ program to pass structure as an argument// to the functions using Call By Reference Method #include <bits/stdc++.h>using namespace std; struct number { int n;}; // Accepts structure as an argument// using call by reference methodvoid increment(number& n2){ n2.n++;} void initializeFunction(){ number n1; // assigning value to n n1.n = 10; cout << " number before calling " << "increment function:" << n1.n << endl; // calling increment function increment(n1); cout << "number after calling" << " increment function:" << n1.n;} // Driver codeint main(){ // Calling function to do required task initializeFunction(); return 0;} number before calling increment function:10 number after calling increment function:11 How to return a structure from the functions? To return a structure from a function the return type should be a structure only. Examples: // C++ program to return a structure from// a function using Call By Value Method #include <iostream>#include <stdlib.h> using namespace std; // required structurestruct Employee { int Id; string Name;}; // return type of the function is structureEmployee data(Employee E){ // Assigning the values to elements E.Id = 45; E.Name = "aman"; // returning structure return (E);} // Driver codeint main(){ // creating object of Employee Employee Emp; // calling function data to assign value Emp = data(Emp); // display the output cout << "Employee Id: " << Emp.Id; cout << "\nEmployee Name: " << Emp.Name; return 0;} Employee Id: 45 Employee Name: aman C-Structure & Union cpp-structure C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Dec, 2019" }, { "code": null, "e": 216, "s": 54, "text": "A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type." }, { "code": null, "e": 271, "s": 216, "text": "How to pass structure as an argument to the functions?" }, { "code": null, "e": 333, "s": 271, "text": "Passing of structure to the function can be done in two ways:" }, { "code": null, "e": 391, "s": 333, "text": "By passing all the elements to the function individually." }, { "code": null, "e": 440, "s": 391, "text": "By passing the entire structure to the function." }, { "code": null, "e": 575, "s": 440, "text": "In this article, entire structure is passed to the function. This can be done using call by reference as well as call by value method." }, { "code": null, "e": 614, "s": 575, "text": "Examples 1: Using Call By Value Method" }, { "code": "// C++ program to pass structure as an argument// to the functions using Call By Value Method #include <bits/stdc++.h>using namespace std; struct Distance { int kilometer; int meter;}; // accepts distance as its parametersvoid TotalDistance(Distance d1, Distance d2){ // creating a new instance of the structure Distance d; // assigning value to new instance of structure d.kilometer = d1.kilometer + d2.kilometer + (d1.meter + d2.meter) / 1000; d.meter = (d1.meter + d2.meter) % 1000; cout << \"Total distance:\"; cout << \"kilometer: \" << d.kilometer << endl; cout << \"meter: \" << d.meter << endl;} // Function that initialises the value// and calls TotalDistance functionvoid initializeFunction(){ // creating two instances of Distance Distance Distance1, Distance2; // assigning values to structure elements Distance1.kilometer = 10; Distance1.meter = 455; Distance2.kilometer = 9; Distance2.meter = 745; // calling function with (structure) // distance as parameters TotalDistance(Distance1, Distance2);} // Driver code0int main(){ // Calling function to do required task initializeFunction(); return 0;}", "e": 1886, "s": 614, "text": null }, { "code": null, "e": 1927, "s": 1886, "text": "Total distance:kilometer: 20\nmeter: 200\n" }, { "code": null, "e": 1970, "s": 1927, "text": "Examples 2: Using Call By Reference Method" }, { "code": "// C++ program to pass structure as an argument// to the functions using Call By Reference Method #include <bits/stdc++.h>using namespace std; struct number { int n;}; // Accepts structure as an argument// using call by reference methodvoid increment(number& n2){ n2.n++;} void initializeFunction(){ number n1; // assigning value to n n1.n = 10; cout << \" number before calling \" << \"increment function:\" << n1.n << endl; // calling increment function increment(n1); cout << \"number after calling\" << \" increment function:\" << n1.n;} // Driver codeint main(){ // Calling function to do required task initializeFunction(); return 0;}", "e": 2678, "s": 1970, "text": null }, { "code": null, "e": 2766, "s": 2678, "text": "number before calling increment function:10\nnumber after calling increment function:11\n" }, { "code": null, "e": 2812, "s": 2766, "text": "How to return a structure from the functions?" }, { "code": null, "e": 2894, "s": 2812, "text": "To return a structure from a function the return type should be a structure only." }, { "code": null, "e": 2904, "s": 2894, "text": "Examples:" }, { "code": "// C++ program to return a structure from// a function using Call By Value Method #include <iostream>#include <stdlib.h> using namespace std; // required structurestruct Employee { int Id; string Name;}; // return type of the function is structureEmployee data(Employee E){ // Assigning the values to elements E.Id = 45; E.Name = \"aman\"; // returning structure return (E);} // Driver codeint main(){ // creating object of Employee Employee Emp; // calling function data to assign value Emp = data(Emp); // display the output cout << \"Employee Id: \" << Emp.Id; cout << \"\\nEmployee Name: \" << Emp.Name; return 0;}", "e": 3578, "s": 2904, "text": null }, { "code": null, "e": 3615, "s": 3578, "text": "Employee Id: 45\nEmployee Name: aman\n" }, { "code": null, "e": 3635, "s": 3615, "text": "C-Structure & Union" }, { "code": null, "e": 3649, "s": 3635, "text": "cpp-structure" }, { "code": null, "e": 3662, "s": 3649, "text": "C++ Programs" } ]
Multicollinearity in Data
27 Sep, 2021 The variable should have a robust relationship with independent variables. However, any unbiased variables shouldn’t have robust correlations among other independent variables. Collinearity can be a linear affiliation among explanatory variables. Two variables are perfectly collinear if there’s a particular linear relationship between them. Multicollinearity refers to a situation at some stage in which two or greater explanatory variables in the course of a multiple correlation model are pretty linearly related. We’ve perfect multicollinearity if the correlation between impartial variables is good to 1 or -1. In practice, we do not often face ideal multicollinearity for the duration of an information set. More commonly, the difficulty of multicollinearity arises when there’s an approximately linear courting between two or more unbiased variables. In easy words, Multicollinearity can be defined as it’s far an event wherein one or greater of the unbiased variables are strongly correlated with one another. In such incidents, we ought to usually use just one in every correlated impartial variable.VIF(Variance Inflation Factor) is a hallmark of the life of multicollinearity, and statsmodel presents a characteristic to calculate the VIF for each experimental variable and worth of greater than 10 is that the rule of thumb for the possible lifestyles of high multicollinearity. The excellent guiding principle for VIF price is as follows, VIF = 1 manner no correlation exists, VIF > 1, but < 5 then correlation exists. What Causes Multicollinearity? The principal types are: Data-based multicollinearity: as a result of poorly designed experiments, statistics that’s 100% observational, or data collection methods that can’t be manipulated. In some cases, variables could also be particularly correlated (usually way to collecting facts from purely observational studies) and there’s no error on the researcher’s part. For this reason, you ought to behaviour experiments every time possible, placing the extent of the predictor variables beforehand. Structural multicollinearity: because of you, the researcher, when they are attempting to create new predictor variables. Causes for multicollinearity also can consist of: Insufficient facts. In some cases, collecting extra statistics can resolve the issue. Dummy variables could also be incorrectly used. For instance, the researcher may fail to exclude one category, or add a dummy variable for every category (e.g. Spring, summer, autumn, winter. Including a variable within the regression that’s a mixture of other variables. For instance, consisting of “general investment profits” while total investment income = earnings from stocks and bonds + profits from savings interest. Including identical (or almost identical) variables. For instance, weight in pounds and weight in kilos, or investment earnings and savings/bond earnings. Example: You can also locate that multicollinearity may be a characteristic of the making plans of the test. In the material manufacturer case, we can without problems see that advertising and marketing and volume are correlated predictor variables, main to foremost swings inside the impact of marketing while the quantity is and aren’t included within the version. In a similar test, you’ll find out that the product producer may additionally introduce multicollinearity between volume and advertising as it’s far part of the experimental design using assigning an excessive ad price range to cities with smaller stores and an espresso ad finances to cities with larger shops. If you are geared up to re-do the market test, you’ll address this difficulty via restructuring the experiment to make sure an honest aggregate of excessive ad/low volume, excessive ad/high quantity, low ad/high quantity, and low ad/low quantity stores. this may let you remove the multicollinearity in the facts set. It is regularly not possible though, to re-do an experiment. that is regularly why it’s crucial to very cautiously analyze the planning of a controlled experiment before starting so that you’ll avoid by chance causing such problems. If you’ve got located multicollinearity because of the experimental design and also you can’t re-do the experiment, you’ll deal with the multicollinearity by which include controls. inside the case of the cloth producer, it’ll be vital to incorporate extent inside the version as an effect to urge a much higher proper estimate for the impact of advertising. Other answers to addressing multicollinearity in instances like this consist of shrinkage estimations like principal additives regression or partial least-squares analysis.Code: Python code to remove Multicollinearity from the dataset using the VIF factor. python3 # read the datasetimport pandas as pddata = pd.read_csv('https://docs.google.com / spreadsheets / d/e / 2PACX-1vQRtMKSAzDVoUFeP_lvpxSPt0pb7YR3_SPBdnq0_2nIgfZUMB8fMgJXaMETqLmrV3uw2yOqkZLEcTvt / pub?output = csv')data.head(3) # Remove the price from the datasetY = data["price"]iv = data.columnsiv = iv.delete(0)X = data[iv] # calculate the variance inflation factorfrom statsmodels.stats.outliers_influence import variance_inflation_factor as vif # compare with each column[vif(data[iv].values, index) for index in range(len(iv))] # Removing multicollinearity from the dataset using viffrom statsmodels.stats.outliers_influence import variance_inflation_factor as vif # compare with each columnsfor i in range(len(iv)): vif_list = [vif(data[iv].values, index) for index in range(len(iv))] maxvif = max(vif_list) print("Max VIF value is ", maxvif) drop_index = vif_list.index(maxvif) print("For Independent variable", iv[drop_index]) if maxvif > 10: print("Deleting", iv[drop_index]) iv = iv.delete(drop_index) print("Final Independent_variables ", iv) Output: Max VIF value is 15.213540834822062 For Independent variable bedrooms Deleting bedrooms Final Independent_variables Index(['lotsize', 'bathrms', 'stories', 'driveway', 'recroom', 'fullbase', 'gashw', 'airco', 'garagepl', 'prefarea'], dtype='object') Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms Max VIF value is 7.738793387948324 For Independent variable bathrms We can notice that VIF analysis has eliminated bedrooms has its greater than 10, however, stories_one and stories_two has been retained. To test the model performs the common practice is to split the dataset into 80/20 (or 70/30) for train/test respectively and use the training dataset to build the model, then apply the trained model on the test dataset to evaluate the performance of the model. We can also evaluate the performance of a model by finding the r2 score. varshagumber28 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 Reinforcement learning Supervised and Unsupervised learning Search Algorithms in AI Decision Tree Introduction with example 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": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 1564, "s": 28, "text": "The variable should have a robust relationship with independent variables. However, any unbiased variables shouldn’t have robust correlations among other independent variables. Collinearity can be a linear affiliation among explanatory variables. Two variables are perfectly collinear if there’s a particular linear relationship between them. Multicollinearity refers to a situation at some stage in which two or greater explanatory variables in the course of a multiple correlation model are pretty linearly related. We’ve perfect multicollinearity if the correlation between impartial variables is good to 1 or -1. In practice, we do not often face ideal multicollinearity for the duration of an information set. More commonly, the difficulty of multicollinearity arises when there’s an approximately linear courting between two or more unbiased variables. In easy words, Multicollinearity can be defined as it’s far an event wherein one or greater of the unbiased variables are strongly correlated with one another. In such incidents, we ought to usually use just one in every correlated impartial variable.VIF(Variance Inflation Factor) is a hallmark of the life of multicollinearity, and statsmodel presents a characteristic to calculate the VIF for each experimental variable and worth of greater than 10 is that the rule of thumb for the possible lifestyles of high multicollinearity. The excellent guiding principle for VIF price is as follows, VIF = 1 manner no correlation exists, VIF > 1, but < 5 then correlation exists. " }, { "code": null, "e": 1623, "s": 1566, "text": "What Causes Multicollinearity? The principal types are: " }, { "code": null, "e": 2098, "s": 1623, "text": "Data-based multicollinearity: as a result of poorly designed experiments, statistics that’s 100% observational, or data collection methods that can’t be manipulated. In some cases, variables could also be particularly correlated (usually way to collecting facts from purely observational studies) and there’s no error on the researcher’s part. For this reason, you ought to behaviour experiments every time possible, placing the extent of the predictor variables beforehand." }, { "code": null, "e": 2220, "s": 2098, "text": "Structural multicollinearity: because of you, the researcher, when they are attempting to create new predictor variables." }, { "code": null, "e": 2272, "s": 2220, "text": "Causes for multicollinearity also can consist of: " }, { "code": null, "e": 2358, "s": 2272, "text": "Insufficient facts. In some cases, collecting extra statistics can resolve the issue." }, { "code": null, "e": 2550, "s": 2358, "text": "Dummy variables could also be incorrectly used. For instance, the researcher may fail to exclude one category, or add a dummy variable for every category (e.g. Spring, summer, autumn, winter." }, { "code": null, "e": 2783, "s": 2550, "text": "Including a variable within the regression that’s a mixture of other variables. For instance, consisting of “general investment profits” while total investment income = earnings from stocks and bonds + profits from savings interest." }, { "code": null, "e": 2938, "s": 2783, "text": "Including identical (or almost identical) variables. For instance, weight in pounds and weight in kilos, or investment earnings and savings/bond earnings." }, { "code": null, "e": 4785, "s": 2938, "text": "Example: You can also locate that multicollinearity may be a characteristic of the making plans of the test. In the material manufacturer case, we can without problems see that advertising and marketing and volume are correlated predictor variables, main to foremost swings inside the impact of marketing while the quantity is and aren’t included within the version. In a similar test, you’ll find out that the product producer may additionally introduce multicollinearity between volume and advertising as it’s far part of the experimental design using assigning an excessive ad price range to cities with smaller stores and an espresso ad finances to cities with larger shops. If you are geared up to re-do the market test, you’ll address this difficulty via restructuring the experiment to make sure an honest aggregate of excessive ad/low volume, excessive ad/high quantity, low ad/high quantity, and low ad/low quantity stores. this may let you remove the multicollinearity in the facts set. It is regularly not possible though, to re-do an experiment. that is regularly why it’s crucial to very cautiously analyze the planning of a controlled experiment before starting so that you’ll avoid by chance causing such problems. If you’ve got located multicollinearity because of the experimental design and also you can’t re-do the experiment, you’ll deal with the multicollinearity by which include controls. inside the case of the cloth producer, it’ll be vital to incorporate extent inside the version as an effect to urge a much higher proper estimate for the impact of advertising. Other answers to addressing multicollinearity in instances like this consist of shrinkage estimations like principal additives regression or partial least-squares analysis.Code: Python code to remove Multicollinearity from the dataset using the VIF factor. " }, { "code": null, "e": 4795, "s": 4787, "text": "python3" }, { "code": "# read the datasetimport pandas as pddata = pd.read_csv('https://docs.google.com / spreadsheets / d/e / 2PACX-1vQRtMKSAzDVoUFeP_lvpxSPt0pb7YR3_SPBdnq0_2nIgfZUMB8fMgJXaMETqLmrV3uw2yOqkZLEcTvt / pub?output = csv')data.head(3) # Remove the price from the datasetY = data[\"price\"]iv = data.columnsiv = iv.delete(0)X = data[iv] # calculate the variance inflation factorfrom statsmodels.stats.outliers_influence import variance_inflation_factor as vif # compare with each column[vif(data[iv].values, index) for index in range(len(iv))] # Removing multicollinearity from the dataset using viffrom statsmodels.stats.outliers_influence import variance_inflation_factor as vif # compare with each columnsfor i in range(len(iv)): vif_list = [vif(data[iv].values, index) for index in range(len(iv))] maxvif = max(vif_list) print(\"Max VIF value is \", maxvif) drop_index = vif_list.index(maxvif) print(\"For Independent variable\", iv[drop_index]) if maxvif > 10: print(\"Deleting\", iv[drop_index]) iv = iv.delete(drop_index) print(\"Final Independent_variables \", iv)", "e": 5918, "s": 4795, "text": null }, { "code": null, "e": 5928, "s": 5918, "text": "Output: " }, { "code": null, "e": 6883, "s": 5928, "text": "Max VIF value is 15.213540834822062\nFor Independent variable bedrooms\nDeleting bedrooms\nFinal Independent_variables Index(['lotsize', 'bathrms', 'stories', 'driveway', 'recroom', 'fullbase',\n 'gashw', 'airco', 'garagepl', 'prefarea'],\n dtype='object')\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms\nMax VIF value is 7.738793387948324\nFor Independent variable bathrms" }, { "code": null, "e": 7355, "s": 6883, "text": "We can notice that VIF analysis has eliminated bedrooms has its greater than 10, however, stories_one and stories_two has been retained. To test the model performs the common practice is to split the dataset into 80/20 (or 70/30) for train/test respectively and use the training dataset to build the model, then apply the trained model on the test dataset to evaluate the performance of the model. We can also evaluate the performance of a model by finding the r2 score. " }, { "code": null, "e": 7370, "s": 7355, "text": "varshagumber28" }, { "code": null, "e": 7384, "s": 7370, "text": "sumitgumber28" }, { "code": null, "e": 7401, "s": 7384, "text": "Machine Learning" }, { "code": null, "e": 7408, "s": 7401, "text": "Python" }, { "code": null, "e": 7425, "s": 7408, "text": "Machine Learning" }, { "code": null, "e": 7523, "s": 7425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7546, "s": 7523, "text": "ML | Linear Regression" }, { "code": null, "e": 7569, "s": 7546, "text": "Reinforcement learning" }, { "code": null, "e": 7606, "s": 7569, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 7630, "s": 7606, "text": "Search Algorithms in AI" }, { "code": null, "e": 7670, "s": 7630, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 7698, "s": 7670, "text": "Read JSON file using Python" }, { "code": null, "e": 7748, "s": 7698, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7770, "s": 7748, "text": "Python map() function" } ]
Java Program to Return the Elements at Odd Positions in a List
17 Dec, 2020 Given a List, the task is to return the elements at Odd positions in a list. Let’s consider the following list. Clearly, we can see that elements 20, 40, 60 are at Odd Positions as the index of the list is zero-based. Now we should return these elements. Approach 1: Initialize a temporary value with zero. Now traverse through the list. At each iteration check the temporary value if value equals to odd then return that element otherwise just continue. After each iteration increment the temporary value by 1. However, this can be done without using temporary value. Since the data in the list is stored using fixed index therefore we can directly check if the index is odd or even and return the element accordingly Example: Java // Java Program to Return the Elements// at Odd Positions in a Listimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Creating our list from above illustration List<Integer> my_list = new ArrayList<Integer>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); // creating a temp_value for checking index int temp_val = 0; // using a for-each loop to // iterate through the list System.out.print("Elements at odd position are : "); for (Integer numbers : my_list) { if (temp_val % 2 != 0) { System.out.print(numbers + " "); } temp_val += 1; } }} Elements at odd position are : 20 40 60 Approach 2: Traverse the list starting from position 1. Now increment the position by 2 after each iteration. By doing this we always end up in an odd position. Iteration 1: 1+2=3 Iteration 2: 2+3=5 Iteration 3: 5+2=7 And so on. Return the value of the element during each iteration. Example: Java // Java Program to Return the Elements// at Odd Positions in a List import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // creating list from above illustration List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); // iterating list from position one and incrementing // the index value by 2 System.out.print( "Elements at odd positions are : "); for (int i = 1; i < 6; i = i + 2) { System.out.print(my_list.get(i) + " "); } }} Elements at odd positions are : 20 40 60 java-list 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": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 140, "s": 28, "text": "Given a List, the task is to return the elements at Odd positions in a list. Let’s consider the following list." }, { "code": null, "e": 283, "s": 140, "text": "Clearly, we can see that elements 20, 40, 60 are at Odd Positions as the index of the list is zero-based. Now we should return these elements." }, { "code": null, "e": 295, "s": 283, "text": "Approach 1:" }, { "code": null, "e": 335, "s": 295, "text": "Initialize a temporary value with zero." }, { "code": null, "e": 366, "s": 335, "text": "Now traverse through the list." }, { "code": null, "e": 483, "s": 366, "text": "At each iteration check the temporary value if value equals to odd then return that element otherwise just continue." }, { "code": null, "e": 540, "s": 483, "text": "After each iteration increment the temporary value by 1." }, { "code": null, "e": 751, "s": 540, "text": "However, this can be done without using temporary value. Since the data in the list is stored using fixed index therefore we can directly check if the index is odd or even and return the element accordingly " }, { "code": null, "e": 760, "s": 751, "text": "Example:" }, { "code": null, "e": 765, "s": 760, "text": "Java" }, { "code": "// Java Program to Return the Elements// at Odd Positions in a Listimport java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Creating our list from above illustration List<Integer> my_list = new ArrayList<Integer>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); // creating a temp_value for checking index int temp_val = 0; // using a for-each loop to // iterate through the list System.out.print(\"Elements at odd position are : \"); for (Integer numbers : my_list) { if (temp_val % 2 != 0) { System.out.print(numbers + \" \"); } temp_val += 1; } }}", "e": 1577, "s": 765, "text": null }, { "code": null, "e": 1617, "s": 1577, "text": "Elements at odd position are : 20 40 60" }, { "code": null, "e": 1629, "s": 1617, "text": "Approach 2:" }, { "code": null, "e": 1673, "s": 1629, "text": "Traverse the list starting from position 1." }, { "code": null, "e": 1778, "s": 1673, "text": "Now increment the position by 2 after each iteration. By doing this we always end up in an odd position." }, { "code": null, "e": 1797, "s": 1778, "text": "Iteration 1: 1+2=3" }, { "code": null, "e": 1816, "s": 1797, "text": "Iteration 2: 2+3=5" }, { "code": null, "e": 1835, "s": 1816, "text": "Iteration 3: 5+2=7" }, { "code": null, "e": 1846, "s": 1835, "text": "And so on." }, { "code": null, "e": 1901, "s": 1846, "text": "Return the value of the element during each iteration." }, { "code": null, "e": 1910, "s": 1901, "text": "Example:" }, { "code": null, "e": 1915, "s": 1910, "text": "Java" }, { "code": "// Java Program to Return the Elements// at Odd Positions in a List import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // creating list from above illustration List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); // iterating list from position one and incrementing // the index value by 2 System.out.print( \"Elements at odd positions are : \"); for (int i = 1; i < 6; i = i + 2) { System.out.print(my_list.get(i) + \" \"); } }}", "e": 2610, "s": 1915, "text": null }, { "code": null, "e": 2651, "s": 2610, "text": "Elements at odd positions are : 20 40 60" }, { "code": null, "e": 2661, "s": 2651, "text": "java-list" }, { "code": null, "e": 2668, "s": 2661, "text": "Picked" }, { "code": null, "e": 2673, "s": 2668, "text": "Java" }, { "code": null, "e": 2687, "s": 2673, "text": "Java Programs" }, { "code": null, "e": 2692, "s": 2687, "text": "Java" }, { "code": null, "e": 2790, "s": 2692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2805, "s": 2790, "text": "Stream In Java" }, { "code": null, "e": 2826, "s": 2805, "text": "Introduction to Java" }, { "code": null, "e": 2847, "s": 2826, "text": "Constructors in Java" }, { "code": null, "e": 2866, "s": 2847, "text": "Exceptions in Java" }, { "code": null, "e": 2883, "s": 2866, "text": "Generics in Java" }, { "code": null, "e": 2909, "s": 2883, "text": "Java Programming Examples" }, { "code": null, "e": 2943, "s": 2909, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2990, "s": 2943, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3028, "s": 2990, "text": "Factory method design pattern in Java" } ]
C Program to print all permutations of a given string
10 Dec, 2021 A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB Here is a solution that is used as a basis in backtracking. C // C program to print all permutations // with duplicates allowed #include <stdio.h> #include <string.h> /* Function to swap values at two pointers */void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */void permute(char *a, int l, int r) { int i; if (l == r) printf("%s\n", a); else { for (i = l; i <= r; i++) { swap((a + l), (a + i)); permute(a, l + 1, r); //backtrack swap((a + l), (a + i)); } } } // Driver codeint main() { char str[] = "ABC"; int n = strlen(str); permute(str, 0, n-1); return 0; } Output: ABC ACB BAC BCA CBA CAB Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(r – l) Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? C++ Program to check Prime Number How to Append a Character to a String in C Producer Consumer Problem in C Program to find Prime Numbers Between given Interval C program to sort an array in ascending order Set, Clear and Toggle a given bit of a number in C time() function in C
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Dec, 2021" }, { "code": null, "e": 260, "s": 52, "text": "A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. " }, { "code": null, "e": 324, "s": 260, "text": "Source: Mathword(http://mathworld.wolfram.com/Permutation.html)" }, { "code": null, "e": 390, "s": 324, "text": "Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB" }, { "code": null, "e": 450, "s": 390, "text": "Here is a solution that is used as a basis in backtracking." }, { "code": null, "e": 452, "s": 450, "text": "C" }, { "code": "// C program to print all permutations // with duplicates allowed #include <stdio.h> #include <string.h> /* Function to swap values at two pointers */void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */void permute(char *a, int l, int r) { int i; if (l == r) printf(\"%s\\n\", a); else { for (i = l; i <= r; i++) { swap((a + l), (a + i)); permute(a, l + 1, r); //backtrack swap((a + l), (a + i)); } } } // Driver codeint main() { char str[] = \"ABC\"; int n = strlen(str); permute(str, 0, n-1); return 0; } ", "e": 1291, "s": 452, "text": null }, { "code": null, "e": 1300, "s": 1291, "text": "Output: " }, { "code": null, "e": 1324, "s": 1300, "text": "ABC\nACB\nBAC\nBCA\nCBA\nCAB" }, { "code": null, "e": 1358, "s": 1324, "text": "Algorithm Paradigm: Backtracking " }, { "code": null, "e": 1469, "s": 1358, "text": "Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 1495, "s": 1469, "text": "Auxiliary Space: O(r – l)" }, { "code": null, "e": 1831, "s": 1495, "text": "Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL" }, { "code": null, "e": 1950, "s": 1831, "text": "Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 1961, "s": 1950, "text": "C Programs" }, { "code": null, "e": 2059, "s": 1961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2094, "s": 2059, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 2135, "s": 2094, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 2194, "s": 2135, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 2228, "s": 2194, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 2271, "s": 2228, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 2302, "s": 2271, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 2355, "s": 2302, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 2401, "s": 2355, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 2452, "s": 2401, "text": "Set, Clear and Toggle a given bit of a number in C" } ]
Java Program for Matrix Chain Multiplication | DP-8
12 Dec, 2018 Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: (ABC)D = (AB)(CD) = A(BCD) = .... However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations. Clearly the first parenthesization requires less number of operations. Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. Input: p[] = {40, 20, 30, 10, 30} Output: 26000 There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 Input: p[] = {10, 20, 30, 40, 30} Output: 30000 There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 Input: p[] = {10, 20, 30} Output: 6000 There are only two matrices of dimensions 10x20 and 20x30. So there is only one way to multiply the matrices, cost of which is 10*20*30 Following is a recursive implementation that simply follows the above optimal substructure property. Java /* A naive recursive implementation that simply follows the above optimal substructure property */class MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int i, int j) { if (i == j) return 0; int min = Integer.MAX_VALUE; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver program to test above function public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4, 3 }; int n = arr.length; System.out.println("Minimum number of multiplications is " + MatrixChainOrder(arr, 1, n - 1)); }}/* This code is contributed by Rajat Mishra*/ Minimum number of multiplications is 30 Dynamic Programming Solution Java // Dynamic Programming Python implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following algorithmclass MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[][] = new int[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Integer.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1]; } // Driver program to test above function public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4 }; int size = arr.length; System.out.println("Minimum number of multiplications is " + MatrixChainOrder(arr, size)); }}/* This code is contributed by Rajat Mishra*/ Minimum number of multiplications is 18 Please refer complete article on Matrix Chain Multiplication | DP-8 for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java SHA-1 Hash Java Program to Convert File to a Byte Array Java Program to Find Sum of Array Elements
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2018" }, { "code": null, "e": 251, "s": 28, "text": "Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications." }, { "code": null, "e": 506, "s": 251, "text": "We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:" }, { "code": null, "e": 545, "s": 506, "text": " (ABC)D = (AB)(CD) = A(BCD) = ....\n" }, { "code": null, "e": 800, "s": 545, "text": "However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then," }, { "code": null, "e": 937, "s": 800, "text": " (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations\n A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.\n" }, { "code": null, "e": 1008, "s": 937, "text": "Clearly the first parenthesization requires less number of operations." }, { "code": null, "e": 1259, "s": 1008, "text": "Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain." }, { "code": null, "e": 2070, "s": 1259, "text": " Input: p[] = {40, 20, 30, 10, 30} \n Output: 26000 \n There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.\n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30\n\n Input: p[] = {10, 20, 30, 40, 30} \n Output: 30000 \n There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. \n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30\n\n Input: p[] = {10, 20, 30} \n Output: 6000 \n There are only two matrices of dimensions 10x20 and 20x30. So there \n is only one way to multiply the matrices, cost of which is 10*20*30\n" }, { "code": null, "e": 2171, "s": 2070, "text": "Following is a recursive implementation that simply follows the above optimal substructure property." }, { "code": null, "e": 2176, "s": 2171, "text": "Java" }, { "code": "/* A naive recursive implementation that simply follows the above optimal substructure property */class MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int i, int j) { if (i == j) return 0; int min = Integer.MAX_VALUE; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (int k = i; k < j; k++) { int count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min; } // Driver program to test above function public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4, 3 }; int n = arr.length; System.out.println(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, 1, n - 1)); }}/* This code is contributed by Rajat Mishra*/", "e": 3392, "s": 2176, "text": null }, { "code": null, "e": 3433, "s": 3392, "text": "Minimum number of multiplications is 30\n" }, { "code": null, "e": 3462, "s": 3433, "text": "Dynamic Programming Solution" }, { "code": null, "e": 3467, "s": 3462, "text": "Java" }, { "code": "// Dynamic Programming Python implementation of Matrix// Chain Multiplication.// See the Cormen book for details of the following algorithmclass MatrixChainMultiplication { // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n static int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[][] = new int[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; if (j == n) continue; m[i][j] = Integer.MAX_VALUE; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1]; } // Driver program to test above function public static void main(String args[]) { int arr[] = new int[] { 1, 2, 3, 4 }; int size = arr.length; System.out.println(\"Minimum number of multiplications is \" + MatrixChainOrder(arr, size)); }}/* This code is contributed by Rajat Mishra*/", "e": 5163, "s": 3467, "text": null }, { "code": null, "e": 5204, "s": 5163, "text": "Minimum number of multiplications is 18\n" }, { "code": null, "e": 5290, "s": 5204, "text": "Please refer complete article on Matrix Chain Multiplication | DP-8 for more details!" }, { "code": null, "e": 5304, "s": 5290, "text": "Java Programs" }, { "code": null, "e": 5402, "s": 5304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5450, "s": 5402, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 5489, "s": 5450, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 5540, "s": 5489, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 5574, "s": 5540, "text": "Java Program to Write into a File" }, { "code": null, "e": 5621, "s": 5574, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 5659, "s": 5621, "text": "Java Program to Read a File to String" }, { "code": null, "e": 5691, "s": 5659, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 5702, "s": 5691, "text": "SHA-1 Hash" }, { "code": null, "e": 5747, "s": 5702, "text": "Java Program to Convert File to a Byte Array" } ]
Time when minute hand and hour hand coincide
09 Mar, 2021 Given time in hours, find the time in minute at which the minute hand and hour hand coincide in next one hour.Examples : Input : 3 Output : (180/11) minutes Input :7 Output : (420/11) minutes Approach : 1. Take two variables for hour “h1 and h2” and then find the angle “theta” [theta = (30 * h1)] and then divide it by “11” to find the time in minute(m). We are dividing with 11, because the hands of a clock coincide 11s time in 12 hours and 22 times in 24 hours :Formula : This can be calculated using the formula for time h1 to h2 means [11m / 2 – 30 (h1)] this implies [ m = ((30 * h1) * 2) / 11 ] ] [ m = (theta * 2) / 11 ] where [theta = (30 * h1) ]where A and B are hours i.e if given hour is (2, 3) then A = 2 and B = 3 . C++ JAVA Python3 C# PHP Javascript // CPP code to find the minute at which// the minute hand and hour hand coincide#include <bits/stdc++.h>using namespace std; // function to find the minutevoid find_time(int h1){ // finding the angle between minute // hand and the first hour hand int theta = 30 * h1; cout << "(" << (theta * 2) << "/" << "11" << ")" << " minutes";} // Driver codeint main() { int h1 = 3; find_time(h1); return 0;} // Java code to find the minute // at which the minute hand and// hour hand coincideimport java.io.*; class GFG{ // function to find the minute static void find_time(int h1) { // finding the angle between // minute hand and the first // hour hand int theta = 30 * h1; System.out.println("(" + theta * 2 + "/" + " 11 ) minutes"); } //Driver Code public static void main (String[] args) { int h1 = 3; find_time(h1); }} // This code is contributed by// upendra singh bartwal # Python3 code to find the# minute at which the minute# hand and hour hand coincide # Function to find the minutedef find_time(h1): # Finding the angle between # minute hand and the first # hour hand theta = 30 * h1 print("(", end = "") print((theta * 2),"/ 11) minutes") # Driver codeh1 = 3find_time(h1) # This code is contributed by# Smitha Dinesh Semwal // C# code to find the minute// at which the minute hand// and hour hand coincideusing System; class GFG{ // function to find the minute static void find_time(int h1) { // finding the angle between minute // hand and the first hour hand int theta = 30 * h1; Console.WriteLine("(" + theta * 2 + "/" + " 11 )minutes"); } //Driver Code public static void Main() { int h1 = 3; find_time(h1); }} // This code is contributed by vt_m. <?php// PHP code to find the minute// at which the minute hand and// hour hand coincide // function to find the minutefunction find_time($h1){ // finding the angle between // minute hand and the first // hour hand $theta = 30 * $h1; echo("(" . ($theta * 2) . "/" . "11" . ")" . " minutes");} // Driver code$h1 = 3;find_time($h1); // This code is contributed by Ajit.?> <script> // JavaScript code to find the minute at which// the minute hand and hour hand coincide // function to find the minutefunction find_time(h1){// finding the angle between minute// hand and the first hour handtheta = 30 * h1;document.write("(" + (theta * 2) + "/" + "11" + ")" + " minutes");} // Driver codeh1 = 3;find_time(h1); // This code is contributed by Surbhi Tyagi. </script> (180/11) minutes jit_t surbhityagi15 date-time-program Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Mar, 2021" }, { "code": null, "e": 176, "s": 53, "text": "Given time in hours, find the time in minute at which the minute hand and hour hand coincide in next one hour.Examples : " }, { "code": null, "e": 249, "s": 176, "text": "Input : 3 \nOutput : (180/11) minutes\n\nInput :7\nOutput : (420/11) minutes" }, { "code": null, "e": 791, "s": 251, "text": "Approach : 1. Take two variables for hour “h1 and h2” and then find the angle “theta” [theta = (30 * h1)] and then divide it by “11” to find the time in minute(m). We are dividing with 11, because the hands of a clock coincide 11s time in 12 hours and 22 times in 24 hours :Formula : This can be calculated using the formula for time h1 to h2 means [11m / 2 – 30 (h1)] this implies [ m = ((30 * h1) * 2) / 11 ] ] [ m = (theta * 2) / 11 ] where [theta = (30 * h1) ]where A and B are hours i.e if given hour is (2, 3) then A = 2 and B = 3 . " }, { "code": null, "e": 795, "s": 791, "text": "C++" }, { "code": null, "e": 800, "s": 795, "text": "JAVA" }, { "code": null, "e": 808, "s": 800, "text": "Python3" }, { "code": null, "e": 811, "s": 808, "text": "C#" }, { "code": null, "e": 815, "s": 811, "text": "PHP" }, { "code": null, "e": 826, "s": 815, "text": "Javascript" }, { "code": "// CPP code to find the minute at which// the minute hand and hour hand coincide#include <bits/stdc++.h>using namespace std; // function to find the minutevoid find_time(int h1){ // finding the angle between minute // hand and the first hour hand int theta = 30 * h1; cout << \"(\" << (theta * 2) << \"/\" << \"11\" << \")\" << \" minutes\";} // Driver codeint main() { int h1 = 3; find_time(h1); return 0;}", "e": 1251, "s": 826, "text": null }, { "code": "// Java code to find the minute // at which the minute hand and// hour hand coincideimport java.io.*; class GFG{ // function to find the minute static void find_time(int h1) { // finding the angle between // minute hand and the first // hour hand int theta = 30 * h1; System.out.println(\"(\" + theta * 2 + \"/\" + \" 11 ) minutes\"); } //Driver Code public static void main (String[] args) { int h1 = 3; find_time(h1); }} // This code is contributed by// upendra singh bartwal", "e": 1839, "s": 1251, "text": null }, { "code": "# Python3 code to find the# minute at which the minute# hand and hour hand coincide # Function to find the minutedef find_time(h1): # Finding the angle between # minute hand and the first # hour hand theta = 30 * h1 print(\"(\", end = \"\") print((theta * 2),\"/ 11) minutes\") # Driver codeh1 = 3find_time(h1) # This code is contributed by# Smitha Dinesh Semwal", "e": 2215, "s": 1839, "text": null }, { "code": "// C# code to find the minute// at which the minute hand// and hour hand coincideusing System; class GFG{ // function to find the minute static void find_time(int h1) { // finding the angle between minute // hand and the first hour hand int theta = 30 * h1; Console.WriteLine(\"(\" + theta * 2 + \"/\" + \" 11 )minutes\"); } //Driver Code public static void Main() { int h1 = 3; find_time(h1); }} // This code is contributed by vt_m.", "e": 2753, "s": 2215, "text": null }, { "code": "<?php// PHP code to find the minute// at which the minute hand and// hour hand coincide // function to find the minutefunction find_time($h1){ // finding the angle between // minute hand and the first // hour hand $theta = 30 * $h1; echo(\"(\" . ($theta * 2) . \"/\" . \"11\" . \")\" . \" minutes\");} // Driver code$h1 = 3;find_time($h1); // This code is contributed by Ajit.?>", "e": 3163, "s": 2753, "text": null }, { "code": "<script> // JavaScript code to find the minute at which// the minute hand and hour hand coincide // function to find the minutefunction find_time(h1){// finding the angle between minute// hand and the first hour handtheta = 30 * h1;document.write(\"(\" + (theta * 2) + \"/\" + \"11\" + \")\" + \" minutes\");} // Driver codeh1 = 3;find_time(h1); // This code is contributed by Surbhi Tyagi. </script>", "e": 3563, "s": 3163, "text": null }, { "code": null, "e": 3580, "s": 3563, "text": "(180/11) minutes" }, { "code": null, "e": 3588, "s": 3582, "text": "jit_t" }, { "code": null, "e": 3602, "s": 3588, "text": "surbhityagi15" }, { "code": null, "e": 3620, "s": 3602, "text": "date-time-program" }, { "code": null, "e": 3633, "s": 3620, "text": "Mathematical" }, { "code": null, "e": 3646, "s": 3633, "text": "Mathematical" } ]
Tryit Editor v3.6 - Show Python
username = input("Enter username:") print("Username is: " + username)
[ { "code": null, "e": 36, "s": 0, "text": "username = input(\"Enter username:\")" } ]
Conda + Google Colab. A guide to installing Conda when using... | by David R. Pugh | Towards Data Science
Conda is the recommended environment and package management solution for a number of popular data science tools including Pandas, Scikit-Learn, PyTorch, NVIDIA Rapids and many others. Conda also dramatically simplifies the process of installing popular deep learning tools like TensorFlow. Google Colab is a free service providing interactive computing resources via a user interface that is very similar to Jupyter notebooks, runs on Google Cloud Platform (GCP), and provides free access to GPUs and TPUs. Google Colab is a great teaching platform and is also perhaps the only free solution available for sharing GPU or TPU accelerated code with your peers. Unfortunately, Conda is not available by default on Google Colab and getting Conda installed and working properly within Google Colab’s default Python environment is a bit of a chore. In this article, I will walk you through the process that I go through when I need to use Conda to install packages when working in Google Colab. First, you need to confirm which Python is being used by default in Google Colab. Running the following command returns the absolute path to the default Python executable. !which python # should return /usr/local/bin/python Now check the version number of this default Python. !python --version At time of writing the above command returns Python 3.6.9. This means that, in order to use all of the preinstalled Google Colab packages, you will need to install a version of Miniconda that is compatible with Python 3.6 by default. More recent versions (i.e., 4.5.12+) of Miniconda target either Python 3.7 or Python 3.8 by default. The most recent version of Miniconda that targets Python 3.6 is Miniconda 4.5.4 so this is the version that you should install. Finally, check to see if the PYTHONPATH variable has been set. !echo $PYTHONPATH At the time of writing this command returns only /env/python (oddly this is a directory that doesn’t seem to exist within Google Colab filesystem). Typically, it is a good idea to unset the PYTHONPATH variable before installing Miniconda as it can cause problems if there are packages installed and accessible via directories included in the PYTHONPATH that are not compatible with the version of Python included with Miniconda. You can unset the PYTHONPATH variable with the following command. This step is optional but if you don’t unset this variable then you will see a warning message after installing Miniconda. %env PYTHONPATH= When executed in a Google Colab cell, the code below will download the installer script for the appropriate version of Miniconda and install it into /usr/local. Installing directly into /usr/local, rather than into the default location ~/miniconda3, insures that Conda and all its required dependencies will be automatically available for use within Google Colab. %%bashMINICONDA_INSTALLER_SCRIPT=Miniconda3-4.5.4-Linux-x86_64.shMINICONDA_PREFIX=/usr/localwget https://repo.continuum.io/miniconda/$MINICONDA_INSTALLER_SCRIPTchmod +x $MINICONDA_INSTALLER_SCRIPT./$MINICONDA_INSTALLER_SCRIPT -b -f -p $MINICONDA_PREFIX Once you have installed Miniconda you should be able to see that the Conda executable is available... !which conda # should return /usr/local/bin/conda ...and that the version number is correct. !conda --version # should return 4.5.4 Note that while installing Miniconda does not appear to impact the Python executable... !which python # still returns /usr/local/bin/python ...however, Miniconda has actually installed a slightly different version of Python. !python --version # now returns Python 3.6.5 :: Anaconda, Inc. Now that you have installed Conda you need to update Conda and all its dependencies to their most recent versions without updating Python to 3.7 (or 3.8). The conda install command below actually updates Conda to the most recent version whilst holding the Python version fixed at 3.6. The conda update command then updates all of Conda’s dependencies to their most recent versions. %%bashconda install --channel defaults conda python=3.6 --yesconda update --channel defaults --all --yes Now you can confirm the update by checking the version number for Conda. !conda --version # now returns 4.8.3 Also, note that the Python version has changed yet again. !python --version # now returns Python 3.6.10 :: Anaconda, Inc. Now that you have installed Miniconda you need to add the directory where Conda will install packages to the list of directories that Python will search when looking for modules to import. You can see the current list of directories that Python will search when looking for modules to import by inspecting the sys.path. import syssys.path As of this writing the sys.path on Google Colab looks as follows. ['', '/env/python', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', # pre-installed packages '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.6/dist-packages/IPython/extensions', '/root/.ipython'] Note that the preinstalled packages included with Google Colab are installed into the /usr/local/lib/python3.6/dist-packages directory. You can get an idea of what packages are available by simply listing the contents of this directory. !ls /usr/local/lib/python3.6/dist-packages Any package that you install with Conda will be installed into the directory /usr/local/lib/python3.6/site-packages so you will need to add this directory to sys.path in order for these packages to be available for import. import sys_ = (sys.path .append("/usr/local/lib/python3.6/site-packages")) Note that because the /usr/local/lib/python3.6/dist-packages directory containing the pre-installed Google Colab packages appears ahead of the /usr/local/lib/python3.6/site-packages directory where Conda installs packages, the version of a package available via Google Colab will take precedence over any version of the same package installed via Conda. Now all you need to do is install you favorite packages. Just remember to include the --yes flag when installing your packages to avoid getting prompted to confirm the package plan. !conda install --channel conda-forge featuretools --yes In this article, I covered the process that I use to install and configure Miniconda when I need to use Conda to manage packages on Google Colab. Hopefully, this will help you the next time you need to share a Conda-managed data science project on Google Colab.
[ { "code": null, "e": 462, "s": 172, "text": "Conda is the recommended environment and package management solution for a number of popular data science tools including Pandas, Scikit-Learn, PyTorch, NVIDIA Rapids and many others. Conda also dramatically simplifies the process of installing popular deep learning tools like TensorFlow." }, { "code": null, "e": 1015, "s": 462, "text": "Google Colab is a free service providing interactive computing resources via a user interface that is very similar to Jupyter notebooks, runs on Google Cloud Platform (GCP), and provides free access to GPUs and TPUs. Google Colab is a great teaching platform and is also perhaps the only free solution available for sharing GPU or TPU accelerated code with your peers. Unfortunately, Conda is not available by default on Google Colab and getting Conda installed and working properly within Google Colab’s default Python environment is a bit of a chore." }, { "code": null, "e": 1161, "s": 1015, "text": "In this article, I will walk you through the process that I go through when I need to use Conda to install packages when working in Google Colab." }, { "code": null, "e": 1333, "s": 1161, "text": "First, you need to confirm which Python is being used by default in Google Colab. Running the following command returns the absolute path to the default Python executable." }, { "code": null, "e": 1385, "s": 1333, "text": "!which python # should return /usr/local/bin/python" }, { "code": null, "e": 1438, "s": 1385, "text": "Now check the version number of this default Python." }, { "code": null, "e": 1456, "s": 1438, "text": "!python --version" }, { "code": null, "e": 1919, "s": 1456, "text": "At time of writing the above command returns Python 3.6.9. This means that, in order to use all of the preinstalled Google Colab packages, you will need to install a version of Miniconda that is compatible with Python 3.6 by default. More recent versions (i.e., 4.5.12+) of Miniconda target either Python 3.7 or Python 3.8 by default. The most recent version of Miniconda that targets Python 3.6 is Miniconda 4.5.4 so this is the version that you should install." }, { "code": null, "e": 1982, "s": 1919, "text": "Finally, check to see if the PYTHONPATH variable has been set." }, { "code": null, "e": 2000, "s": 1982, "text": "!echo $PYTHONPATH" }, { "code": null, "e": 2148, "s": 2000, "text": "At the time of writing this command returns only /env/python (oddly this is a directory that doesn’t seem to exist within Google Colab filesystem)." }, { "code": null, "e": 2429, "s": 2148, "text": "Typically, it is a good idea to unset the PYTHONPATH variable before installing Miniconda as it can cause problems if there are packages installed and accessible via directories included in the PYTHONPATH that are not compatible with the version of Python included with Miniconda." }, { "code": null, "e": 2618, "s": 2429, "text": "You can unset the PYTHONPATH variable with the following command. This step is optional but if you don’t unset this variable then you will see a warning message after installing Miniconda." }, { "code": null, "e": 2635, "s": 2618, "text": "%env PYTHONPATH=" }, { "code": null, "e": 2999, "s": 2635, "text": "When executed in a Google Colab cell, the code below will download the installer script for the appropriate version of Miniconda and install it into /usr/local. Installing directly into /usr/local, rather than into the default location ~/miniconda3, insures that Conda and all its required dependencies will be automatically available for use within Google Colab." }, { "code": null, "e": 3252, "s": 2999, "text": "%%bashMINICONDA_INSTALLER_SCRIPT=Miniconda3-4.5.4-Linux-x86_64.shMINICONDA_PREFIX=/usr/localwget https://repo.continuum.io/miniconda/$MINICONDA_INSTALLER_SCRIPTchmod +x $MINICONDA_INSTALLER_SCRIPT./$MINICONDA_INSTALLER_SCRIPT -b -f -p $MINICONDA_PREFIX" }, { "code": null, "e": 3354, "s": 3252, "text": "Once you have installed Miniconda you should be able to see that the Conda executable is available..." }, { "code": null, "e": 3404, "s": 3354, "text": "!which conda # should return /usr/local/bin/conda" }, { "code": null, "e": 3447, "s": 3404, "text": "...and that the version number is correct." }, { "code": null, "e": 3486, "s": 3447, "text": "!conda --version # should return 4.5.4" }, { "code": null, "e": 3574, "s": 3486, "text": "Note that while installing Miniconda does not appear to impact the Python executable..." }, { "code": null, "e": 3626, "s": 3574, "text": "!which python # still returns /usr/local/bin/python" }, { "code": null, "e": 3711, "s": 3626, "text": "...however, Miniconda has actually installed a slightly different version of Python." }, { "code": null, "e": 3774, "s": 3711, "text": "!python --version # now returns Python 3.6.5 :: Anaconda, Inc." }, { "code": null, "e": 4156, "s": 3774, "text": "Now that you have installed Conda you need to update Conda and all its dependencies to their most recent versions without updating Python to 3.7 (or 3.8). The conda install command below actually updates Conda to the most recent version whilst holding the Python version fixed at 3.6. The conda update command then updates all of Conda’s dependencies to their most recent versions." }, { "code": null, "e": 4261, "s": 4156, "text": "%%bashconda install --channel defaults conda python=3.6 --yesconda update --channel defaults --all --yes" }, { "code": null, "e": 4334, "s": 4261, "text": "Now you can confirm the update by checking the version number for Conda." }, { "code": null, "e": 4371, "s": 4334, "text": "!conda --version # now returns 4.8.3" }, { "code": null, "e": 4429, "s": 4371, "text": "Also, note that the Python version has changed yet again." }, { "code": null, "e": 4493, "s": 4429, "text": "!python --version # now returns Python 3.6.10 :: Anaconda, Inc." }, { "code": null, "e": 4813, "s": 4493, "text": "Now that you have installed Miniconda you need to add the directory where Conda will install packages to the list of directories that Python will search when looking for modules to import. You can see the current list of directories that Python will search when looking for modules to import by inspecting the sys.path." }, { "code": null, "e": 4832, "s": 4813, "text": "import syssys.path" }, { "code": null, "e": 4898, "s": 4832, "text": "As of this writing the sys.path on Google Colab looks as follows." }, { "code": null, "e": 5181, "s": 4898, "text": "['', '/env/python', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', # pre-installed packages '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.6/dist-packages/IPython/extensions', '/root/.ipython']" }, { "code": null, "e": 5418, "s": 5181, "text": "Note that the preinstalled packages included with Google Colab are installed into the /usr/local/lib/python3.6/dist-packages directory. You can get an idea of what packages are available by simply listing the contents of this directory." }, { "code": null, "e": 5461, "s": 5418, "text": "!ls /usr/local/lib/python3.6/dist-packages" }, { "code": null, "e": 5684, "s": 5461, "text": "Any package that you install with Conda will be installed into the directory /usr/local/lib/python3.6/site-packages so you will need to add this directory to sys.path in order for these packages to be available for import." }, { "code": null, "e": 5766, "s": 5684, "text": "import sys_ = (sys.path .append(\"/usr/local/lib/python3.6/site-packages\"))" }, { "code": null, "e": 6120, "s": 5766, "text": "Note that because the /usr/local/lib/python3.6/dist-packages directory containing the pre-installed Google Colab packages appears ahead of the /usr/local/lib/python3.6/site-packages directory where Conda installs packages, the version of a package available via Google Colab will take precedence over any version of the same package installed via Conda." }, { "code": null, "e": 6302, "s": 6120, "text": "Now all you need to do is install you favorite packages. Just remember to include the --yes flag when installing your packages to avoid getting prompted to confirm the package plan." }, { "code": null, "e": 6358, "s": 6302, "text": "!conda install --channel conda-forge featuretools --yes" } ]
Implementing the Perceptron Algorithm in Python | by Suraj Verma | Towards Data Science
In this article, we are going to look at the Perceptron Algorithm, which is the most basic single-layered neural network used for binary classification. First, we will look at the Unit Step Function and see how the Perceptron Algorithm classifies and then have a look at the perceptron update rule. Finally, we will plot the decision boundary for our data. We will use the data with only two features, and there will be two classes since Perceptron is a binary classifier. We will implement all the code using Python NumPy, and visualize/plot using Matplotlib. towardsdatascience.com towardsdatascience.com The Perceptron algorithm was inspired by the basic processing units in the brain, called neurons, and how they process signals. It was invented by Frank Rosenblatt, using the McCulloch-Pitts neuron and the findings of Hebb. Perceptron Research Paper. A Perceptron Algorithm is not something widely used in practice. We study it mostly for historical reasons and also because it is the most basic and simple single-layered neural network. Let us try to understand the Perceptron algorithm using the following data as a motivating example. from sklearn import datasetsX, y = datasets.make_blobs(n_samples=150,n_features=2, centers=2,cluster_std=1.05, random_state=2)#Plottingfig = plt.figure(figsize=(10,8))plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], 'r^')plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], 'bs')plt.xlabel("feature 1")plt.ylabel("feature 2")plt.title('Random Classification Data with 2 classes') There are two classes, red and green, and we want to separate them by drawing a straight line between them. Or, more formally, we want to learn a set of parameters theta to find an optimal hyperplane(straight line for our data) that separates the two classes. For Linear regression our hypothesis (y_hat) was theta.X. Then, for binary classification in Logistic Regression, we needed to output probabilities between 0 and 1, so we modified the hypothesis as — sigmoid(theta.X). We applied the sigmoid function over the dot product of input features and parameters because we needed to squish our output between 0 and 1. For the Perceptron algorithm, we apply a different function over theta.X , which is the Unit Step Function, which is defined as — where, Unlike Logistic Regression which outputs probability between 0 and 1, the Perceptron outputs values that are either 0 or 1 exactly. This function says that if the output(theta.X) is greater than or equal to zero, then the model will classify 1(red for example)and if the output is less than zero, the model will classify as 0(green for example). And that is how the perception algorithm classifies. Let’s look at the Unit Step Function graphically — We can see for z≥0, g(z) = 1 and for z<0, g(z) = 0. Let’s code the step function. def step_func(z): return 1.0 if (z > 0) else 0.0 We can visually understand the Perceptron by looking at the above image. For every training example, we first take the dot product of input features and parameters, theta. Then, we apply the Unit Step Function to make the prediction(y_hat). And if the prediction is wrong or in other words the model has misclassified that example, we make the update for the parameters theta. We don’t update when the prediction is correct (or the same as the true/target value y). Let’s see what the update rule is. The perception update rule is very similar to the Gradient Descent update rule. The following is the update rule — Note that even though the Perceptron algorithm may look similar to logistic regression, it is actually a very different type of algorithm, since it is difficult to endow the perceptron’s predictions with meaningful probabilistic interpretations, or derive the perceptron as a maximum likelihood estimation algorithm. (From Andrew Ng Course) Let’s code it. See comments(#). def perceptron(X, y, lr, epochs): # X --> Inputs. # y --> labels/target. # lr --> learning rate. # epochs --> Number of iterations. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing parapeters(theta) to zeros. # +1 in n+1 for the bias term. theta = np.zeros((n+1,1)) # Empty list to store how many examples were # misclassified at every iteration. n_miss_list = [] # Training. for epoch in range(epochs): # variable to store #misclassified. n_miss = 0 # looping for every example. for idx, x_i in enumerate(X): # Insering 1 for bias, X0 = 1. x_i = np.insert(x_i, 0, 1).reshape(-1,1) # Calculating prediction/hypothesis. y_hat = step_func(np.dot(x_i.T, theta)) # Updating if the example is misclassified. if (np.squeeze(y_hat) - y[idx]) != 0: theta += lr*((y[idx] - y_hat)*x_i) # Incrementing by 1. n_miss += 1 # Appending number of misclassified examples # at every iteration. n_miss_list.append(n_miss) return theta, n_miss_list We know that the model makes a prediction of — y=1 when y_hat ≥ 0 y=0 when y_hat < 0 So, theta.X = 0 is going to be our Decision boundary. The following code for plotting the Decision Boundary only works when we have only two features in X. See comments(#). def plot_decision_boundary(X, theta): # X --> Inputs # theta --> parameters # The Line is y=mx+c # So, Equate mx+c = theta0.X0 + theta1.X1 + theta2.X2 # Solving we find m and c x1 = [min(X[:,0]), max(X[:,0])] m = -theta[1]/theta[2] c = -theta[0]/theta[2] x2 = m*x1 + c # Plotting fig = plt.figure(figsize=(10,8)) plt.plot(X[:, 0][y==0], X[:, 1][y==0], "r^") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") plt.xlabel("feature 1") plt.ylabel("feature 2") plt.title(’Perceptron Algorithm’) plt.plot(x1, x2, 'y-') theta, miss_l = perceptron(X, y, 0.5, 100)plot_decision_boundary(X, theta) We can see from the above decision boundary graph that we are able to separate the green and blue classes perfectly. Meaning, We get an accuracy of 100%. It is only a linear classifier, can never separate data that are not linearly separable.The algorithm is used only for Binary Classification problems. It is only a linear classifier, can never separate data that are not linearly separable. The algorithm is used only for Binary Classification problems. Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon. Check out the Machine Learning from scratch series — Part 1: Linear Regression from scratch in Python Part 2: Locally Weighted Linear Regression in Python Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression Part 4: Polynomial Regression From Scratch in Python Part 5: Logistic Regression From Scratch in Python
[ { "code": null, "e": 471, "s": 172, "text": "In this article, we are going to look at the Perceptron Algorithm, which is the most basic single-layered neural network used for binary classification. First, we will look at the Unit Step Function and see how the Perceptron Algorithm classifies and then have a look at the perceptron update rule." }, { "code": null, "e": 733, "s": 471, "text": "Finally, we will plot the decision boundary for our data. We will use the data with only two features, and there will be two classes since Perceptron is a binary classifier. We will implement all the code using Python NumPy, and visualize/plot using Matplotlib." }, { "code": null, "e": 756, "s": 733, "text": "towardsdatascience.com" }, { "code": null, "e": 779, "s": 756, "text": "towardsdatascience.com" }, { "code": null, "e": 1030, "s": 779, "text": "The Perceptron algorithm was inspired by the basic processing units in the brain, called neurons, and how they process signals. It was invented by Frank Rosenblatt, using the McCulloch-Pitts neuron and the findings of Hebb. Perceptron Research Paper." }, { "code": null, "e": 1217, "s": 1030, "text": "A Perceptron Algorithm is not something widely used in practice. We study it mostly for historical reasons and also because it is the most basic and simple single-layered neural network." }, { "code": null, "e": 1317, "s": 1217, "text": "Let us try to understand the Perceptron algorithm using the following data as a motivating example." }, { "code": null, "e": 1733, "s": 1317, "text": "from sklearn import datasetsX, y = datasets.make_blobs(n_samples=150,n_features=2, centers=2,cluster_std=1.05, random_state=2)#Plottingfig = plt.figure(figsize=(10,8))plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], 'r^')plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], 'bs')plt.xlabel(\"feature 1\")plt.ylabel(\"feature 2\")plt.title('Random Classification Data with 2 classes')" }, { "code": null, "e": 1993, "s": 1733, "text": "There are two classes, red and green, and we want to separate them by drawing a straight line between them. Or, more formally, we want to learn a set of parameters theta to find an optimal hyperplane(straight line for our data) that separates the two classes." }, { "code": null, "e": 2353, "s": 1993, "text": "For Linear regression our hypothesis (y_hat) was theta.X. Then, for binary classification in Logistic Regression, we needed to output probabilities between 0 and 1, so we modified the hypothesis as — sigmoid(theta.X). We applied the sigmoid function over the dot product of input features and parameters because we needed to squish our output between 0 and 1." }, { "code": null, "e": 2483, "s": 2353, "text": "For the Perceptron algorithm, we apply a different function over theta.X , which is the Unit Step Function, which is defined as —" }, { "code": null, "e": 2490, "s": 2483, "text": "where," }, { "code": null, "e": 2622, "s": 2490, "text": "Unlike Logistic Regression which outputs probability between 0 and 1, the Perceptron outputs values that are either 0 or 1 exactly." }, { "code": null, "e": 2889, "s": 2622, "text": "This function says that if the output(theta.X) is greater than or equal to zero, then the model will classify 1(red for example)and if the output is less than zero, the model will classify as 0(green for example). And that is how the perception algorithm classifies." }, { "code": null, "e": 2940, "s": 2889, "text": "Let’s look at the Unit Step Function graphically —" }, { "code": null, "e": 2992, "s": 2940, "text": "We can see for z≥0, g(z) = 1 and for z<0, g(z) = 0." }, { "code": null, "e": 3022, "s": 2992, "text": "Let’s code the step function." }, { "code": null, "e": 3078, "s": 3022, "text": "def step_func(z): return 1.0 if (z > 0) else 0.0" }, { "code": null, "e": 3319, "s": 3078, "text": "We can visually understand the Perceptron by looking at the above image. For every training example, we first take the dot product of input features and parameters, theta. Then, we apply the Unit Step Function to make the prediction(y_hat)." }, { "code": null, "e": 3544, "s": 3319, "text": "And if the prediction is wrong or in other words the model has misclassified that example, we make the update for the parameters theta. We don’t update when the prediction is correct (or the same as the true/target value y)." }, { "code": null, "e": 3579, "s": 3544, "text": "Let’s see what the update rule is." }, { "code": null, "e": 3694, "s": 3579, "text": "The perception update rule is very similar to the Gradient Descent update rule. The following is the update rule —" }, { "code": null, "e": 4011, "s": 3694, "text": "Note that even though the Perceptron algorithm may look similar to logistic regression, it is actually a very different type of algorithm, since it is difficult to endow the perceptron’s predictions with meaningful probabilistic interpretations, or derive the perceptron as a maximum likelihood estimation algorithm." }, { "code": null, "e": 4035, "s": 4011, "text": "(From Andrew Ng Course)" }, { "code": null, "e": 4067, "s": 4035, "text": "Let’s code it. See comments(#)." }, { "code": null, "e": 5350, "s": 4067, "text": "def perceptron(X, y, lr, epochs): # X --> Inputs. # y --> labels/target. # lr --> learning rate. # epochs --> Number of iterations. # m-> number of training examples # n-> number of features m, n = X.shape # Initializing parapeters(theta) to zeros. # +1 in n+1 for the bias term. theta = np.zeros((n+1,1)) # Empty list to store how many examples were # misclassified at every iteration. n_miss_list = [] # Training. for epoch in range(epochs): # variable to store #misclassified. n_miss = 0 # looping for every example. for idx, x_i in enumerate(X): # Insering 1 for bias, X0 = 1. x_i = np.insert(x_i, 0, 1).reshape(-1,1) # Calculating prediction/hypothesis. y_hat = step_func(np.dot(x_i.T, theta)) # Updating if the example is misclassified. if (np.squeeze(y_hat) - y[idx]) != 0: theta += lr*((y[idx] - y_hat)*x_i) # Incrementing by 1. n_miss += 1 # Appending number of misclassified examples # at every iteration. n_miss_list.append(n_miss) return theta, n_miss_list" }, { "code": null, "e": 5397, "s": 5350, "text": "We know that the model makes a prediction of —" }, { "code": null, "e": 5416, "s": 5397, "text": "y=1 when y_hat ≥ 0" }, { "code": null, "e": 5435, "s": 5416, "text": "y=0 when y_hat < 0" }, { "code": null, "e": 5489, "s": 5435, "text": "So, theta.X = 0 is going to be our Decision boundary." }, { "code": null, "e": 5591, "s": 5489, "text": "The following code for plotting the Decision Boundary only works when we have only two features in X." }, { "code": null, "e": 5608, "s": 5591, "text": "See comments(#)." }, { "code": null, "e": 6179, "s": 5608, "text": "def plot_decision_boundary(X, theta): # X --> Inputs # theta --> parameters # The Line is y=mx+c # So, Equate mx+c = theta0.X0 + theta1.X1 + theta2.X2 # Solving we find m and c x1 = [min(X[:,0]), max(X[:,0])] m = -theta[1]/theta[2] c = -theta[0]/theta[2] x2 = m*x1 + c # Plotting fig = plt.figure(figsize=(10,8)) plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"r^\") plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\") plt.xlabel(\"feature 1\") plt.ylabel(\"feature 2\") plt.title(’Perceptron Algorithm’) plt.plot(x1, x2, 'y-')" }, { "code": null, "e": 6254, "s": 6179, "text": "theta, miss_l = perceptron(X, y, 0.5, 100)plot_decision_boundary(X, theta)" }, { "code": null, "e": 6408, "s": 6254, "text": "We can see from the above decision boundary graph that we are able to separate the green and blue classes perfectly. Meaning, We get an accuracy of 100%." }, { "code": null, "e": 6559, "s": 6408, "text": "It is only a linear classifier, can never separate data that are not linearly separable.The algorithm is used only for Binary Classification problems." }, { "code": null, "e": 6648, "s": 6559, "text": "It is only a linear classifier, can never separate data that are not linearly separable." }, { "code": null, "e": 6711, "s": 6648, "text": "The algorithm is used only for Binary Classification problems." }, { "code": null, "e": 6839, "s": 6711, "text": "Thanks for reading. For questions, comments, concerns, talk to be in the response section. More ML from scratch is coming soon." }, { "code": null, "e": 6892, "s": 6839, "text": "Check out the Machine Learning from scratch series —" }, { "code": null, "e": 6941, "s": 6892, "text": "Part 1: Linear Regression from scratch in Python" }, { "code": null, "e": 6994, "s": 6941, "text": "Part 2: Locally Weighted Linear Regression in Python" }, { "code": null, "e": 7079, "s": 6994, "text": "Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression" }, { "code": null, "e": 7132, "s": 7079, "text": "Part 4: Polynomial Regression From Scratch in Python" } ]
Clone a linked list with next and random pointer | Set 1 - GeeksforGeeks
17 Feb, 2022 You are given a Double Link List with one pointer of each node pointing to the next node just like in a single link list. The second pointer however CAN point to any node in the list and not just the previous node. Now write a program in O(n) time to duplicate this list. That is, write a program which will create a copy of this list. Let us call the second pointer as arbit pointer as it can point to any arbitrary node in the linked list. Figure 1 Arbitrary pointers are shown in red and next pointers in black Method 1 (Uses O(n) extra space) This method stores the next and arbitrary mappings (of original list) in an array first, then modifies the original Linked List (to create copy), creates a copy. And finally restores the original list. 1) Create all nodes in copy linked list using next pointers. 2) Store the node and its next pointer mappings of original linked list. 3) Change next pointer of all nodes in original linked list to point to the corresponding node in copy linked list. Following diagram shows status of both Linked Lists after above 3 steps. The red arrow shows arbit pointers and black arrow shows next pointers. Figure 2 4) Change the arbit pointer of all nodes in copy linked list to point to corresponding node in original linked list. 5) Now construct the arbit pointer in copy linked list as below and restore the next pointer of nodes in the original linked list. copy_list_node->arbit = copy_list_node->arbit->arbit->next; copy_list_node = copy_list_node->next; 6) Restore the next pointers in original linked list from the stored mappings(in step 2). Time Complexity: O(n) Auxiliary Space: O(n) Method 2 (Uses Constant Extra Space) Thanks to Saravanan Mani for providing this solution. This solution works using constant space. 1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N after the Nth node 2) Now copy the arbitrary link in this fashion original->next->arbitrary = original->arbitrary->next; /*TRAVERSE TWO NODES*/ This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary. 3) Now restore the original and copy linked lists in this fashion in a single loop. original->next = original->next->next; copy->next = copy->next->next; 4) Make sure that last element of original->next is NULL. Refer below post for implementation of this method. Clone a linked list with next and random pointer in O(1) space Time Complexity: O(n) Auxiliary Space: O(1) Refer Following Post for Hashing based Implementation. Clone a linked list with next and random pointer | Set 2 Asked by Varun Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. RohithReddyVajrala nikhatkhan11 Amazon BankBazaar MakeMyTrip Microsoft Morgan Stanley Ola Cabs Snapdeal Linked List Morgan Stanley Amazon Microsoft Snapdeal MakeMyTrip Ola Cabs BankBazaar Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments LinkedList in Java Linked List vs Array Queue - Linked List Implementation Merge two sorted linked lists Detect loop in a linked list Find the middle of a given linked list Implement a stack using singly linked list Implementing a Linked List in Java using Class Merge Sort for Linked Lists Circular Linked List | Set 1 (Introduction and Applications)
[ { "code": null, "e": 24267, "s": 24239, "text": "\n17 Feb, 2022" }, { "code": null, "e": 24604, "s": 24267, "text": "You are given a Double Link List with one pointer of each node pointing to the next node just like in a single link list. The second pointer however CAN point to any node in the list and not just the previous node. Now write a program in O(n) time to duplicate this list. That is, write a program which will create a copy of this list. " }, { "code": null, "e": 24711, "s": 24604, "text": "Let us call the second pointer as arbit pointer as it can point to any arbitrary node in the linked list. " }, { "code": null, "e": 24724, "s": 24715, "text": "Figure 1" }, { "code": null, "e": 24788, "s": 24724, "text": "Arbitrary pointers are shown in red and next pointers in black " }, { "code": null, "e": 25026, "s": 24790, "text": "Method 1 (Uses O(n) extra space) This method stores the next and arbitrary mappings (of original list) in an array first, then modifies the original Linked List (to create copy), creates a copy. And finally restores the original list. " }, { "code": null, "e": 25422, "s": 25026, "text": "1) Create all nodes in copy linked list using next pointers. 2) Store the node and its next pointer mappings of original linked list. 3) Change next pointer of all nodes in original linked list to point to the corresponding node in copy linked list. Following diagram shows status of both Linked Lists after above 3 steps. The red arrow shows arbit pointers and black arrow shows next pointers. " }, { "code": null, "e": 25435, "s": 25426, "text": "Figure 2" }, { "code": null, "e": 25684, "s": 25435, "text": "4) Change the arbit pointer of all nodes in copy linked list to point to corresponding node in original linked list. 5) Now construct the arbit pointer in copy linked list as below and restore the next pointer of nodes in the original linked list. " }, { "code": null, "e": 25822, "s": 25686, "text": " copy_list_node->arbit =\n copy_list_node->arbit->arbit->next;\n copy_list_node = copy_list_node->next; " }, { "code": null, "e": 25913, "s": 25822, "text": "6) Restore the next pointers in original linked list from the stored mappings(in step 2). " }, { "code": null, "e": 25960, "s": 25913, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 26348, "s": 25960, "text": "Method 2 (Uses Constant Extra Space) Thanks to Saravanan Mani for providing this solution. This solution works using constant space. 1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N after the Nth node 2) Now copy the arbitrary link in this fashion " }, { "code": null, "e": 26433, "s": 26348, "text": " original->next->arbitrary = original->arbitrary->next; /*TRAVERSE \nTWO NODES*/" }, { "code": null, "e": 26649, "s": 26433, "text": "This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy of arbitrary. 3) Now restore the original and copy linked lists in this fashion in a single loop. " }, { "code": null, "e": 26729, "s": 26649, "text": " original->next = original->next->next;\n copy->next = copy->next->next;" }, { "code": null, "e": 26788, "s": 26729, "text": "4) Make sure that last element of original->next is NULL. " }, { "code": null, "e": 26904, "s": 26788, "text": "Refer below post for implementation of this method. Clone a linked list with next and random pointer in O(1) space " }, { "code": null, "e": 26949, "s": 26904, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 27062, "s": 26949, "text": "Refer Following Post for Hashing based Implementation. Clone a linked list with next and random pointer | Set 2 " }, { "code": null, "e": 27211, "s": 27062, "text": "Asked by Varun Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27230, "s": 27211, "text": "RohithReddyVajrala" }, { "code": null, "e": 27243, "s": 27230, "text": "nikhatkhan11" }, { "code": null, "e": 27250, "s": 27243, "text": "Amazon" }, { "code": null, "e": 27261, "s": 27250, "text": "BankBazaar" }, { "code": null, "e": 27272, "s": 27261, "text": "MakeMyTrip" }, { "code": null, "e": 27282, "s": 27272, "text": "Microsoft" }, { "code": null, "e": 27297, "s": 27282, "text": "Morgan Stanley" }, { "code": null, "e": 27306, "s": 27297, "text": "Ola Cabs" }, { "code": null, "e": 27315, "s": 27306, "text": "Snapdeal" }, { "code": null, "e": 27327, "s": 27315, "text": "Linked List" }, { "code": null, "e": 27342, "s": 27327, "text": "Morgan Stanley" }, { "code": null, "e": 27349, "s": 27342, "text": "Amazon" }, { "code": null, "e": 27359, "s": 27349, "text": "Microsoft" }, { "code": null, "e": 27368, "s": 27359, "text": "Snapdeal" }, { "code": null, "e": 27379, "s": 27368, "text": "MakeMyTrip" }, { "code": null, "e": 27388, "s": 27379, "text": "Ola Cabs" }, { "code": null, "e": 27399, "s": 27388, "text": "BankBazaar" }, { "code": null, "e": 27411, "s": 27399, "text": "Linked List" }, { "code": null, "e": 27509, "s": 27411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27518, "s": 27509, "text": "Comments" }, { "code": null, "e": 27531, "s": 27518, "text": "Old Comments" }, { "code": null, "e": 27550, "s": 27531, "text": "LinkedList in Java" }, { "code": null, "e": 27571, "s": 27550, "text": "Linked List vs Array" }, { "code": null, "e": 27606, "s": 27571, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 27636, "s": 27606, "text": "Merge two sorted linked lists" }, { "code": null, "e": 27665, "s": 27636, "text": "Detect loop in a linked list" }, { "code": null, "e": 27704, "s": 27665, "text": "Find the middle of a given linked list" }, { "code": null, "e": 27747, "s": 27704, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 27794, "s": 27747, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 27822, "s": 27794, "text": "Merge Sort for Linked Lists" } ]
BK-Tree | Introduction & Implementation - GeeksforGeeks
20 Apr, 2022 BK Tree or Burkhard Keller Tree is a data structure that is used to perform spell check based on Edit Distance (Levenshtein distance) concept. BK trees are also used for approximate string matching. Various auto correct feature in many software can be implemented based on this data structure. Pre-requisites : Edit distance Problem Metric tree Let’s say we have a dictionary of words and then we have some other words which are to be checked in the dictionary for spelling errors. We need to have collection of all words in the dictionary which are very close to the given word. For instance if we are checking a word “ruk” we will have {“truck”,”buck”,”duck”,......}. Therefore, spelling mistake can be corrected by deleting a character from the word or adding a new character in the word or by replacing the character in the word by some appropriate one. Therefore, we will be using the edit distance as a measure for correctness and matching of the misspelled word from the words in our dictionary.Now, let’s see the structure of our BK Tree. Like all other trees, BK Tree consists of nodes and edges. The nodes in the BK Tree will represent the individual words in our dictionary and there will be exactly the same number of nodes as the number of words in our dictionary. The edge will contain some integer weight that will tell us about the edit-distance from one node to another. Lets say we have an edge from node u to node v having some edge-weight w, then w is the edit-distance required to turn the string u to v. Consider our dictionary with words : { “help” , “hell” , “hello”}. Therefore, for this dictionary our BK Tree will look like the below one. Every node in the BK Tree will have exactly one child with same edit-distance. In case, if we encounter some collision for edit-distance while inserting, we will then propagate the insertion process down the children until we find an appropriate parent for the string node. Every insertion in the BK Tree will start from our root node. Root node can be any word from our dictionary.For example, let’s add another word “shell” to the above dictionary. Now our Dict[] = {“help” , “hell” , “hello” , “shell”}. It is now evident that “shell” has same edit-distance as “hello” has from the root node “help” i.e 2. Hence, we encounter a collision. Therefore, we deal this collision by recursively doing this insertion process on the pre-existing colliding node.So, now instead of inserting “shell” at the root node “help“, we will now insert it to the colliding node “hello“. Therefore, now the new node “shell” is added to the tree and it has node “hello” as its parent with the edge-weight of 2(edit-distance). Below pictorial representation describes the BK Tree after this insertion. So, till now we have understood how we will build our BK Tree. Now, the question arises that how to find the closest correct word for our misspelled word? First of all, we need to set a tolerance value. This tolerance value is simply the maximum edit distance from our misspelled word to the correct words in our dictionary. So, to find the eligible correct words within the tolerance limit, Naive approach will be to iterate over all the words in the dictionary and collect the words which are within the tolerance limit. But this approach has O(n*m*n) time complexity(n is the number of words in dict[], m is average size of correct word and n is length of misspelled word) which times out for larger size of dictionary. Therefore, now the BK Tree comes into action. As we know that each node in BK Tree is constructed on basis of edit-distance measure from its parent. Therefore, we will directly be going from root node to specific nodes that lie within the tolerance limit. Lets, say our tolerance limit is TOL and the edit-distance of the current node from the misspelled word is dist. Therefore, now instead of iterating over all its children we will only iterate over its children that have edit distance in range [dist-TOL , dist+TOL]. This will reduce our complexity by a large extent. We will discuss this in our time complexity analysis.Consider the below constructed BK Tree. Let’s say we have a misspelled word “oop” and the tolerance limit is 2. Now, we will see how we will collect the expected correct for the given misspelled word.Iteration 1: We will start checking the edit distance from the root node. D(“oop” -> “help”) = 3. Now we will iterate over its children having edit distance in range [ D-TOL , D+TOL ] i.e [1,5]Iteration 2: Let’s start iterating from the highest possible edit distance child i.e node “loop” with edit distance 4.Now once again we will find its edit distance from our misspelled word. D(“oop”,”loop”) = 1. here D = 1 i.e D <= TOL , so we will add “loop” to the expected correct word list and process its child nodes having edit distance in range [D-TOL,D+TOL] i.e [1,3] Iteration 3: Now, we are at node “troop” . Once again we will check its edit distance from misspelled word . D(“oop”,”troop”)=2 .Here again D <= TOL , hence again we will add “troop” to the expected correct word list. We will proceed the same for all the words in the range [D-TOL,D+TOL] starting from the root node till the bottom most leaf node. This, is similar to a DFS traversal on a tree, with selectively visiting the child nodes whose edge weight lie in some given range.Therefore, at the end we will be left with only 2 expected words for the misspelled word “oop” i.e {“loop”, “troop”} C++ // C++ program to demonstrate working of BK-Tree#include "bits/stdc++.h"using namespace std; // maximum number of words in dict[]#define MAXN 100 // defines the tolerance value#define TOL 2 // defines maximum length of a word#define LEN 10 struct Node{ // stores the word of the current Node string word; // links to other Node in the tree int next[2*LEN]; // constructors Node(string x):word(x) { // initializing next[i] = 0 for(int i=0; i<2*LEN; i++) next[i] = 0; } Node() {}}; // stores the root NodeNode RT; // stores every Node of the treeNode tree[MAXN]; // index for current Node of treeint ptr; int min(int a, int b, int c){ return min(a, min(b, c));} // Edit Distance// Dynamic-Approach O(m*n)int editDistance(string& a,string& b){ int m = a.length(), n = b.length(); int dp[m+1][n+1]; // filling base cases for (int i=0; i<=m; i++) dp[i][0] = i; for (int j=0; j<=n; j++) dp[0][j] = j; // populating matrix using dp-approach for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (a[i-1] != b[j-1]) { dp[i][j] = min( 1 + dp[i-1][j], // deletion 1 + dp[i][j-1], // insertion 1 + dp[i-1][j-1] // replacement ); } else dp[i][j] = dp[i-1][j-1]; } } return dp[m][n];} // adds curr Node to the treevoid add(Node& root,Node& curr){ if (root.word == "" ) { // if it is the first Node // then make it the root Node root = curr; return; } // get its editDistance from the Root Node int dist = editDistance(curr.word,root.word); if (tree[root.next[dist]].word == "") { /* if no Node exists at this dist from root * make it child of root Node*/ // incrementing the pointer for curr Node ptr++; // adding curr Node to the tree tree[ptr] = curr; // curr as child of root Node root.next[dist] = ptr; } else { // recursively find the parent for curr Node add(tree[root.next[dist]],curr); }} vector <string> getSimilarWords(Node& root,string& s){ vector < string > ret; if (root.word == "") return ret; // calculating editdistance of s from root int dist = editDistance(root.word,s); // if dist is less than tolerance value // add it to similar words if (dist <= TOL) ret.push_back(root.word); // iterate over the string having tolerance // in range (dist-TOL , dist+TOL) int start = dist - TOL; if (start < 0) start = 1; while (start <= dist + TOL) { vector <string> tmp = getSimilarWords(tree[root.next[start]],s); for (auto i : tmp) ret.push_back(i); start++; } return ret;} // driver program to run above functionsint main(int argc, char const *argv[]){ // dictionary words string dictionary[] = {"hell","help","shell","smell", "fell","felt","oops","pop","oouch","halt" }; ptr = 0; int sz = sizeof(dictionary)/sizeof(string); // adding dict[] words on to tree for(int i=0; i<sz; i++) { Node tmp = Node(dictionary[i]); add(RT,tmp); } string w1 = "ops"; string w2 = "helt"; vector < string > match = getSimilarWords(RT,w1); cout << "similar words in dictionary for : " << w1 << ":\n"; for (auto x : match) cout << x << endl; match = getSimilarWords(RT,w2); cout << "Correct words in dictionary for " << w2 << ":\n"; for (auto x : match) cout << x << endl; return 0;} similar words in dictionary for : ops: oops pop Correct words in dictionary for helt: hell help shell fell felt halt Time Complexity: It is quite evident that the time complexity majorly depends on the tolerance limit. We will be considering tolerance limit to be 2. Now, roughly estimating, the depth of BK Tree will be log n, where n is the size of dictionary. At every level we are visiting 2 nodes in the tree and performing edit distance calculation. Therefore, our Time Complexity will be O(L1*L2*log n), here L1 is the average length of word in our dictionary and L2 is the length of misspelled. Generally, L1 and L2 will be small. References https://en.wikipedia.org/wiki/BK-tree https://issues.apache.org/jira/browse/LUCENE-2230 This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kalrap615 kapoorsagar226 surinderdawra388 simmytarika5 surindertarika1234 Advanced Data Structure Tree Tree 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 Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 24486, "s": 24458, "text": "\n20 Apr, 2022" }, { "code": null, "e": 24781, "s": 24486, "text": "BK Tree or Burkhard Keller Tree is a data structure that is used to perform spell check based on Edit Distance (Levenshtein distance) concept. BK trees are also used for approximate string matching. Various auto correct feature in many software can be implemented based on this data structure. " }, { "code": null, "e": 24849, "s": 24781, "text": "Pre-requisites : Edit distance Problem\n Metric tree" }, { "code": null, "e": 26030, "s": 24849, "text": "Let’s say we have a dictionary of words and then we have some other words which are to be checked in the dictionary for spelling errors. We need to have collection of all words in the dictionary which are very close to the given word. For instance if we are checking a word “ruk” we will have {“truck”,”buck”,”duck”,......}. Therefore, spelling mistake can be corrected by deleting a character from the word or adding a new character in the word or by replacing the character in the word by some appropriate one. Therefore, we will be using the edit distance as a measure for correctness and matching of the misspelled word from the words in our dictionary.Now, let’s see the structure of our BK Tree. Like all other trees, BK Tree consists of nodes and edges. The nodes in the BK Tree will represent the individual words in our dictionary and there will be exactly the same number of nodes as the number of words in our dictionary. The edge will contain some integer weight that will tell us about the edit-distance from one node to another. Lets say we have an edge from node u to node v having some edge-weight w, then w is the edit-distance required to turn the string u to v." }, { "code": null, "e": 26171, "s": 26030, "text": "Consider our dictionary with words : { “help” , “hell” , “hello”}. Therefore, for this dictionary our BK Tree will look like the below one. " }, { "code": null, "e": 26445, "s": 26171, "text": "Every node in the BK Tree will have exactly one child with same edit-distance. In case, if we encounter some collision for edit-distance while inserting, we will then propagate the insertion process down the children until we find an appropriate parent for the string node." }, { "code": null, "e": 27253, "s": 26445, "text": "Every insertion in the BK Tree will start from our root node. Root node can be any word from our dictionary.For example, let’s add another word “shell” to the above dictionary. Now our Dict[] = {“help” , “hell” , “hello” , “shell”}. It is now evident that “shell” has same edit-distance as “hello” has from the root node “help” i.e 2. Hence, we encounter a collision. Therefore, we deal this collision by recursively doing this insertion process on the pre-existing colliding node.So, now instead of inserting “shell” at the root node “help“, we will now insert it to the colliding node “hello“. Therefore, now the new node “shell” is added to the tree and it has node “hello” as its parent with the edge-weight of 2(edit-distance). Below pictorial representation describes the BK Tree after this insertion." }, { "code": null, "e": 27976, "s": 27253, "text": "So, till now we have understood how we will build our BK Tree. Now, the question arises that how to find the closest correct word for our misspelled word? First of all, we need to set a tolerance value. This tolerance value is simply the maximum edit distance from our misspelled word to the correct words in our dictionary. So, to find the eligible correct words within the tolerance limit, Naive approach will be to iterate over all the words in the dictionary and collect the words which are within the tolerance limit. But this approach has O(n*m*n) time complexity(n is the number of words in dict[], m is average size of correct word and n is length of misspelled word) which times out for larger size of dictionary." }, { "code": null, "e": 28476, "s": 27976, "text": "Therefore, now the BK Tree comes into action. As we know that each node in BK Tree is constructed on basis of edit-distance measure from its parent. Therefore, we will directly be going from root node to specific nodes that lie within the tolerance limit. Lets, say our tolerance limit is TOL and the edit-distance of the current node from the misspelled word is dist. Therefore, now instead of iterating over all its children we will only iterate over its children that have edit distance in range " }, { "code": null, "e": 28643, "s": 28476, "text": "[dist-TOL , dist+TOL]. This will reduce our complexity by a large extent. We will discuss this in our time complexity analysis.Consider the below constructed BK Tree." }, { "code": null, "e": 29371, "s": 28643, "text": "Let’s say we have a misspelled word “oop” and the tolerance limit is 2. Now, we will see how we will collect the expected correct for the given misspelled word.Iteration 1: We will start checking the edit distance from the root node. D(“oop” -> “help”) = 3. Now we will iterate over its children having edit distance in range [ D-TOL , D+TOL ] i.e [1,5]Iteration 2: Let’s start iterating from the highest possible edit distance child i.e node “loop” with edit distance 4.Now once again we will find its edit distance from our misspelled word. D(“oop”,”loop”) = 1. here D = 1 i.e D <= TOL , so we will add “loop” to the expected correct word list and process its child nodes having edit distance in range [D-TOL,D+TOL] i.e [1,3]" }, { "code": null, "e": 29590, "s": 29371, "text": "Iteration 3: Now, we are at node “troop” . Once again we will check its edit distance from misspelled word . D(“oop”,”troop”)=2 .Here again D <= TOL , hence again we will add “troop” to the expected correct word list. " }, { "code": null, "e": 29969, "s": 29590, "text": "We will proceed the same for all the words in the range [D-TOL,D+TOL] starting from the root node till the bottom most leaf node. This, is similar to a DFS traversal on a tree, with selectively visiting the child nodes whose edge weight lie in some given range.Therefore, at the end we will be left with only 2 expected words for the misspelled word “oop” i.e {“loop”, “troop”} " }, { "code": null, "e": 29973, "s": 29969, "text": "C++" }, { "code": "// C++ program to demonstrate working of BK-Tree#include \"bits/stdc++.h\"using namespace std; // maximum number of words in dict[]#define MAXN 100 // defines the tolerance value#define TOL 2 // defines maximum length of a word#define LEN 10 struct Node{ // stores the word of the current Node string word; // links to other Node in the tree int next[2*LEN]; // constructors Node(string x):word(x) { // initializing next[i] = 0 for(int i=0; i<2*LEN; i++) next[i] = 0; } Node() {}}; // stores the root NodeNode RT; // stores every Node of the treeNode tree[MAXN]; // index for current Node of treeint ptr; int min(int a, int b, int c){ return min(a, min(b, c));} // Edit Distance// Dynamic-Approach O(m*n)int editDistance(string& a,string& b){ int m = a.length(), n = b.length(); int dp[m+1][n+1]; // filling base cases for (int i=0; i<=m; i++) dp[i][0] = i; for (int j=0; j<=n; j++) dp[0][j] = j; // populating matrix using dp-approach for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (a[i-1] != b[j-1]) { dp[i][j] = min( 1 + dp[i-1][j], // deletion 1 + dp[i][j-1], // insertion 1 + dp[i-1][j-1] // replacement ); } else dp[i][j] = dp[i-1][j-1]; } } return dp[m][n];} // adds curr Node to the treevoid add(Node& root,Node& curr){ if (root.word == \"\" ) { // if it is the first Node // then make it the root Node root = curr; return; } // get its editDistance from the Root Node int dist = editDistance(curr.word,root.word); if (tree[root.next[dist]].word == \"\") { /* if no Node exists at this dist from root * make it child of root Node*/ // incrementing the pointer for curr Node ptr++; // adding curr Node to the tree tree[ptr] = curr; // curr as child of root Node root.next[dist] = ptr; } else { // recursively find the parent for curr Node add(tree[root.next[dist]],curr); }} vector <string> getSimilarWords(Node& root,string& s){ vector < string > ret; if (root.word == \"\") return ret; // calculating editdistance of s from root int dist = editDistance(root.word,s); // if dist is less than tolerance value // add it to similar words if (dist <= TOL) ret.push_back(root.word); // iterate over the string having tolerance // in range (dist-TOL , dist+TOL) int start = dist - TOL; if (start < 0) start = 1; while (start <= dist + TOL) { vector <string> tmp = getSimilarWords(tree[root.next[start]],s); for (auto i : tmp) ret.push_back(i); start++; } return ret;} // driver program to run above functionsint main(int argc, char const *argv[]){ // dictionary words string dictionary[] = {\"hell\",\"help\",\"shell\",\"smell\", \"fell\",\"felt\",\"oops\",\"pop\",\"oouch\",\"halt\" }; ptr = 0; int sz = sizeof(dictionary)/sizeof(string); // adding dict[] words on to tree for(int i=0; i<sz; i++) { Node tmp = Node(dictionary[i]); add(RT,tmp); } string w1 = \"ops\"; string w2 = \"helt\"; vector < string > match = getSimilarWords(RT,w1); cout << \"similar words in dictionary for : \" << w1 << \":\\n\"; for (auto x : match) cout << x << endl; match = getSimilarWords(RT,w2); cout << \"Correct words in dictionary for \" << w2 << \":\\n\"; for (auto x : match) cout << x << endl; return 0;}", "e": 33704, "s": 29973, "text": null }, { "code": null, "e": 33821, "s": 33704, "text": "similar words in dictionary for : ops:\noops\npop\nCorrect words in dictionary for helt:\nhell\nhelp\nshell\nfell\nfelt\nhalt" }, { "code": null, "e": 34344, "s": 33821, "text": "Time Complexity: It is quite evident that the time complexity majorly depends on the tolerance limit. We will be considering tolerance limit to be 2. Now, roughly estimating, the depth of BK Tree will be log n, where n is the size of dictionary. At every level we are visiting 2 nodes in the tree and performing edit distance calculation. Therefore, our Time Complexity will be O(L1*L2*log n), here L1 is the average length of word in our dictionary and L2 is the length of misspelled. Generally, L1 and L2 will be small. " }, { "code": null, "e": 34356, "s": 34344, "text": "References " }, { "code": null, "e": 34394, "s": 34356, "text": "https://en.wikipedia.org/wiki/BK-tree" }, { "code": null, "e": 34444, "s": 34394, "text": "https://issues.apache.org/jira/browse/LUCENE-2230" }, { "code": null, "e": 34865, "s": 34444, "text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34875, "s": 34865, "text": "kalrap615" }, { "code": null, "e": 34890, "s": 34875, "text": "kapoorsagar226" }, { "code": null, "e": 34907, "s": 34890, "text": "surinderdawra388" }, { "code": null, "e": 34920, "s": 34907, "text": "simmytarika5" }, { "code": null, "e": 34939, "s": 34920, "text": "surindertarika1234" }, { "code": null, "e": 34963, "s": 34939, "text": "Advanced Data Structure" }, { "code": null, "e": 34968, "s": 34963, "text": "Tree" }, { "code": null, "e": 34973, "s": 34968, "text": "Tree" }, { "code": null, "e": 35071, "s": 34973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35113, "s": 35071, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 35159, "s": 35113, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 35237, "s": 35159, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 35247, "s": 35237, "text": "Quad Tree" }, { "code": null, "e": 35297, "s": 35247, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 35347, "s": 35297, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 35382, "s": 35347, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 35416, "s": 35382, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 35457, "s": 35416, "text": "Inorder Tree Traversal without Recursion" } ]
How I Coded Technical Indicators for Bitcoin | Towards Data Science
When it comes to trading, there are a variety of techniques that can be applied to find the most optimum time to invest. Some could look at the financials and see if there is value behind the curtains. Others might look to the daily news and observe how it may influence the current price. Another group might actually look at the price movements in the past and try to discern possible patterns to determine future price movements. Technical Analysis concerns that group that observes past prices and movements to predict future prices. By utilizing technical analysis, we can derive many different patterns just from using an element’s price history. Mathematical formulas that have been developed throughout the past half century have been used to derive novel values just from a stock’s price and volume history. These formula’s returning values are what we call Technical Indicators. When trading a resource such as Bitcoin, there is not much to analyze besides its price history and volume. If you take a look at its Yahoo Finance page and compare it to any random stock’s page, you can see that it is missing some financial information. This is because Bitcoin is not a company but a currency. There are no Balance Sheets, Profit and Loss Statements, etcetera when it comes to Bitcoin. With no fundamental information to go on, we can resort to utilizing Technical Indicators when trading Bitcoin. If we wanted to add more variables to a trading algorithm or a machine learning forecasting model, then we could introduce more features (technical indicators) to the dataset instead of the usual price and volume history. This tactic may help in forecasting future prices when utilizing a machine learning model. Next up, we will be coding out these technical indicators in Python by utilizing its multiple libraries. Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks! The technical indicators that we will be experimenting with are: Relative Strength Index Stochastic Oscillator Simple Moving Average These indicators appear simple enough for us to develop a function to create and introduce new values and features to our dataset. In order to develop these functions, let’s first import the necessary libraries as well as download the most up-to-date price history for Bitcoin. Another option for price history would be to use a financial data API such as EOD Historical Data. It is free to sign up and you’ll have access to vast amounts of financial data. Disclosure: I earn a small commission from any purchases made through the link above. import pandas as pdimport _pickle as pickleimport numpy as npimport matplotlib as pltplt.style.use('bmh')df = pd.read_csv('BTC-USD.csv') Take a look at the Pandas DataFrame when you run this code: Another step after this would be to convert the index into a Datetime format. This is a simple process requiring only a couple lines of code: # Datetime conversiondf['Date'] = pd.to_datetime(df.Date)# Setting the indexdf.set_index('Date', inplace=True) By running these lines of code, visualizing any column or feature from this dataset will be easier. With the data ready for us to manipulate, let’s start by coding out some simple functions that will give us the technical indicator values we need. (The formulas for these indicators can be found in the links with the technical indicators). Once we run these functions on the appropriate columns, we will receive a new set of features derived from these technical indicators. Nice! We were able to successfully feature engineer and introduce this new data into our dataset. But, how do we verify these values? Well, there are options to view online such as stock charts with indicators that will show us the right values at specific times. One option is to compare our values to the Yahoo Finance chart. As we compare our technical indicator values to the chart, we can see that do not match. There may have been an issue with the functions or we missed a calculation here and there. Anyways, our functions are not performing as well as we wanted. Where do we go from here? We could go back and try to fix our code or we could try a more practical approach. This approach will be to use a Technical Analysis library already written and provided for us. Most of the time, using a Python library for these sort of calculations are better than us writing our own functions. The library we will be utilizing is simply called — ta. You can click on the link below for instructions on how to get started with the library: technical-analysis-library-in-python.readthedocs.io The functions provided here are much more versatile than the ones we created so let’s put them to use. # Importing Libraryimport ta# TA's RSIdf['ta_rsi'] = ta.momentum.rsi(df.Close)# TA's Stochastic Oscillatordf['ta_stoch_k'] = ta.momentum.stoch(df.High, df.Low, df.Close)df['ta_stoch_d'] = ta.momentum.stoch_signal(df.High, df.Low, df.Close) Once run the above piece of code we will end up with the DataFrame below: As we can see, the values we created differ quite significantly from TA’s values. We can also check the validity of these values again with Yahoo Finance’s chart and see that they do indeed match. After seeing attempting to create our own technical indicator functions, we found a more optimal approach by importing a technical analysis library. Generally, it is better to utilize a Python library instead of your own written functions because they are usually much more optimized than anything we could possibly code. The library also gives us the option of adding more indicators instead of trying to code it all out ourselves. In the end, we were able to practice coding out some simple algorithms and functions even though they weren’t as accurate as we had hoped. Once we have constructed this new DataFrame filled with new features and values, we now may be able to feed this extra data into machine learning model. The data is in an easily digestible Pandas format for a potential time series forecasting model. Hopefully, we can improve forecasting results by using these extra technical indicators. Follow me on Twitter: @_Marco_Santos_
[ { "code": null, "e": 605, "s": 172, "text": "When it comes to trading, there are a variety of techniques that can be applied to find the most optimum time to invest. Some could look at the financials and see if there is value behind the curtains. Others might look to the daily news and observe how it may influence the current price. Another group might actually look at the price movements in the past and try to discern possible patterns to determine future price movements." }, { "code": null, "e": 1061, "s": 605, "text": "Technical Analysis concerns that group that observes past prices and movements to predict future prices. By utilizing technical analysis, we can derive many different patterns just from using an element’s price history. Mathematical formulas that have been developed throughout the past half century have been used to derive novel values just from a stock’s price and volume history. These formula’s returning values are what we call Technical Indicators." }, { "code": null, "e": 1465, "s": 1061, "text": "When trading a resource such as Bitcoin, there is not much to analyze besides its price history and volume. If you take a look at its Yahoo Finance page and compare it to any random stock’s page, you can see that it is missing some financial information. This is because Bitcoin is not a company but a currency. There are no Balance Sheets, Profit and Loss Statements, etcetera when it comes to Bitcoin." }, { "code": null, "e": 1890, "s": 1465, "text": "With no fundamental information to go on, we can resort to utilizing Technical Indicators when trading Bitcoin. If we wanted to add more variables to a trading algorithm or a machine learning forecasting model, then we could introduce more features (technical indicators) to the dataset instead of the usual price and volume history. This tactic may help in forecasting future prices when utilizing a machine learning model." }, { "code": null, "e": 1995, "s": 1890, "text": "Next up, we will be coding out these technical indicators in Python by utilizing its multiple libraries." }, { "code": null, "e": 2160, "s": 1995, "text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!" }, { "code": null, "e": 2225, "s": 2160, "text": "The technical indicators that we will be experimenting with are:" }, { "code": null, "e": 2249, "s": 2225, "text": "Relative Strength Index" }, { "code": null, "e": 2271, "s": 2249, "text": "Stochastic Oscillator" }, { "code": null, "e": 2293, "s": 2271, "text": "Simple Moving Average" }, { "code": null, "e": 2424, "s": 2293, "text": "These indicators appear simple enough for us to develop a function to create and introduce new values and features to our dataset." }, { "code": null, "e": 2836, "s": 2424, "text": "In order to develop these functions, let’s first import the necessary libraries as well as download the most up-to-date price history for Bitcoin. Another option for price history would be to use a financial data API such as EOD Historical Data. It is free to sign up and you’ll have access to vast amounts of financial data. Disclosure: I earn a small commission from any purchases made through the link above." }, { "code": null, "e": 2973, "s": 2836, "text": "import pandas as pdimport _pickle as pickleimport numpy as npimport matplotlib as pltplt.style.use('bmh')df = pd.read_csv('BTC-USD.csv')" }, { "code": null, "e": 3033, "s": 2973, "text": "Take a look at the Pandas DataFrame when you run this code:" }, { "code": null, "e": 3175, "s": 3033, "text": "Another step after this would be to convert the index into a Datetime format. This is a simple process requiring only a couple lines of code:" }, { "code": null, "e": 3286, "s": 3175, "text": "# Datetime conversiondf['Date'] = pd.to_datetime(df.Date)# Setting the indexdf.set_index('Date', inplace=True)" }, { "code": null, "e": 3386, "s": 3286, "text": "By running these lines of code, visualizing any column or feature from this dataset will be easier." }, { "code": null, "e": 3627, "s": 3386, "text": "With the data ready for us to manipulate, let’s start by coding out some simple functions that will give us the technical indicator values we need. (The formulas for these indicators can be found in the links with the technical indicators)." }, { "code": null, "e": 3762, "s": 3627, "text": "Once we run these functions on the appropriate columns, we will receive a new set of features derived from these technical indicators." }, { "code": null, "e": 3860, "s": 3762, "text": "Nice! We were able to successfully feature engineer and introduce this new data into our dataset." }, { "code": null, "e": 4090, "s": 3860, "text": "But, how do we verify these values? Well, there are options to view online such as stock charts with indicators that will show us the right values at specific times. One option is to compare our values to the Yahoo Finance chart." }, { "code": null, "e": 4334, "s": 4090, "text": "As we compare our technical indicator values to the chart, we can see that do not match. There may have been an issue with the functions or we missed a calculation here and there. Anyways, our functions are not performing as well as we wanted." }, { "code": null, "e": 4657, "s": 4334, "text": "Where do we go from here? We could go back and try to fix our code or we could try a more practical approach. This approach will be to use a Technical Analysis library already written and provided for us. Most of the time, using a Python library for these sort of calculations are better than us writing our own functions." }, { "code": null, "e": 4802, "s": 4657, "text": "The library we will be utilizing is simply called — ta. You can click on the link below for instructions on how to get started with the library:" }, { "code": null, "e": 4854, "s": 4802, "text": "technical-analysis-library-in-python.readthedocs.io" }, { "code": null, "e": 4957, "s": 4854, "text": "The functions provided here are much more versatile than the ones we created so let’s put them to use." }, { "code": null, "e": 5197, "s": 4957, "text": "# Importing Libraryimport ta# TA's RSIdf['ta_rsi'] = ta.momentum.rsi(df.Close)# TA's Stochastic Oscillatordf['ta_stoch_k'] = ta.momentum.stoch(df.High, df.Low, df.Close)df['ta_stoch_d'] = ta.momentum.stoch_signal(df.High, df.Low, df.Close)" }, { "code": null, "e": 5271, "s": 5197, "text": "Once run the above piece of code we will end up with the DataFrame below:" }, { "code": null, "e": 5468, "s": 5271, "text": "As we can see, the values we created differ quite significantly from TA’s values. We can also check the validity of these values again with Yahoo Finance’s chart and see that they do indeed match." }, { "code": null, "e": 6040, "s": 5468, "text": "After seeing attempting to create our own technical indicator functions, we found a more optimal approach by importing a technical analysis library. Generally, it is better to utilize a Python library instead of your own written functions because they are usually much more optimized than anything we could possibly code. The library also gives us the option of adding more indicators instead of trying to code it all out ourselves. In the end, we were able to practice coding out some simple algorithms and functions even though they weren’t as accurate as we had hoped." }, { "code": null, "e": 6379, "s": 6040, "text": "Once we have constructed this new DataFrame filled with new features and values, we now may be able to feed this extra data into machine learning model. The data is in an easily digestible Pandas format for a potential time series forecasting model. Hopefully, we can improve forecasting results by using these extra technical indicators." } ]
Groovy - Break Statement
The break statement is used to alter the flow of control inside loops and switch statements. We have already seen the break statement in action in conjunction with the switch statement. The break statement can also be used with while and for statements. Executing a break statement with any of these looping constructs causes immediate termination of the innermost enclosing loop. The following diagram shows the diagrammatic explanation of the break statement. Following is an example of the break statement − class Example { static void main(String[] args) { int[] array = [0,1,2,3]; for(int i in array) { println(i); if(i == 2) break; } } } The output of the above code would be − 0 1 2 As expected since there is a condition put saying that if the value of i is 2 then break from the loop that is why the last element of the array which is 3 is not printed. 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2619, "s": 2238, "text": "The break statement is used to alter the flow of control inside loops and switch statements. We have already seen the break statement in action in conjunction with the switch statement. The break statement can also be used with while and for statements. Executing a break statement with any of these looping constructs causes immediate termination of the innermost enclosing loop." }, { "code": null, "e": 2700, "s": 2619, "text": "The following diagram shows the diagrammatic explanation of the break statement." }, { "code": null, "e": 2749, "s": 2700, "text": "Following is an example of the break statement −" }, { "code": null, "e": 2937, "s": 2749, "text": "class Example {\n static void main(String[] args) {\n int[] array = [0,1,2,3];\n\t\t\n for(int i in array) {\n println(i);\n if(i == 2)\n break;\n }\n } \n}" }, { "code": null, "e": 2977, "s": 2937, "text": "The output of the above code would be −" }, { "code": null, "e": 2987, "s": 2977, "text": "0 \n1 \n2 \n" }, { "code": null, "e": 3159, "s": 2987, "text": "As expected since there is a condition put saying that if the value of i is 2 then break from the loop that is why the last element of the array which is 3 is not printed." }, { "code": null, "e": 3192, "s": 3159, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3210, "s": 3192, "text": " Krishna Sakinala" }, { "code": null, "e": 3245, "s": 3210, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3263, "s": 3245, "text": " Packt Publishing" }, { "code": null, "e": 3270, "s": 3263, "text": " Print" }, { "code": null, "e": 3281, "s": 3270, "text": " Add Notes" } ]
Ruby on Rails - Models
Model.new # creates a new empty model Model.create( :field ⇒ 'value', :other_field ⇒ 42 ) # creates an object with the passed parameters and saves it Model.find_or_create_by_field( value ) # searches for a record where "field = value", creates # a new record if not found User.find_or_create_by_name_and_email( 'ramjoe', '[email protected]') There are four ways of associating models. has_one, has_many, belongs_to and has_and_belongs_to_many. Assuming the following four entities − def Order < ActiveRecord::Base has_many :line_items belongs_to :customer end def LineItem < ActiveRecord::Base belongs_to :order end def Customer < ActiveRecord::Base has_many :orders has_one :address end def Address < ActiveRecord::Base belongs_to :customer end Consider following relationship − def Category < ActiveRecord::Base has_and_belongs_to_many :products end def Product < ActiveRecord::Base has_and_belongs_to_many :categories end Consider the following relationship now. This depicts how we can use joins while defining relationship. class Author < ActiveRecord::Base has_many :authorships has_many :books, :through ⇒ :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end class Book < ActiveRecord::Base has_one :authorship end @author = Author.find :first # selects all books that the author's authorships belong to. @author.authorships.collect { |a| a.book } selects all books by using the Authorship join model @author.books Check Associations for more details. Print Add Notes Bookmark this page
[ { "code": null, "e": 2449, "s": 2103, "text": "Model.new # creates a new empty model\nModel.create( :field ⇒ 'value', :other_field ⇒ 42 )\n# creates an object with the passed parameters and saves it\n\nModel.find_or_create_by_field( value ) \n# searches for a record where \"field = value\", creates\n# a new record if not found\n\nUser.find_or_create_by_name_and_email( 'ramjoe', '[email protected]')" }, { "code": null, "e": 2590, "s": 2449, "text": "There are four ways of associating models. has_one, has_many, belongs_to and has_and_belongs_to_many. Assuming the following four entities −" }, { "code": null, "e": 2875, "s": 2590, "text": "def Order < ActiveRecord::Base\n has_many :line_items\n belongs_to :customer \nend\n\ndef LineItem < ActiveRecord::Base\n belongs_to :order\nend\n\ndef Customer < ActiveRecord::Base\n has_many :orders\n has_one :address\nend\n\ndef Address < ActiveRecord::Base\n belongs_to :customer\nend" }, { "code": null, "e": 2909, "s": 2875, "text": "Consider following relationship −" }, { "code": null, "e": 3064, "s": 2909, "text": "def Category < ActiveRecord::Base \n has_and_belongs_to_many :products\nend\n\ndef Product < ActiveRecord::Base\n has_and_belongs_to_many :categories \nend" }, { "code": null, "e": 3168, "s": 3064, "text": "Consider the following relationship now. This depicts how we can use joins while defining relationship." }, { "code": null, "e": 3623, "s": 3168, "text": "class Author < ActiveRecord::Base\n has_many :authorships\n has_many :books, :through ⇒ :authorships\nend\n\nclass Authorship < ActiveRecord::Base\n belongs_to :author\n belongs_to :book\nend\n\nclass Book < ActiveRecord::Base\n has_one :authorship\nend\n\n@author = Author.find :first\n# selects all books that the author's authorships belong to.\n\[email protected] { |a| a.book }\nselects all books by using the Authorship join model\[email protected] " }, { "code": null, "e": 3660, "s": 3623, "text": "Check Associations for more details." }, { "code": null, "e": 3667, "s": 3660, "text": " Print" }, { "code": null, "e": 3678, "s": 3667, "text": " Add Notes" } ]
Maximum occured integer | Practice | GeeksforGeeks
Given n integer ranges, the task is to find the maximum occurring integer in these ranges. If more than one such integer exits, find the smallest one. The ranges are given as two arrays L[] and R[]. L[i] consists of starting point of range and R[i] consists of corresponding end point of the range. For example consider the following ranges. L[] = {2, 1, 3}, R[] = {5, 3, 9) Ranges represented by above arrays are. [2, 5] = {2, 3, 4, 5} [1, 3] = {1, 2, 3} [3, 9] = {3, 4, 5, 6, 7, 8, 9} The maximum occurred integer in these ranges is 3. Example 1: Input: n = 4 L[] = {1,4,3,1} R[] = {15,8,5,4} Output: 4 Explanation: The given ranges are [1,15] [4, 8] [3, 5] [1, 4]. The number that is most common or appears most times in the ranges is 4. Example 2: Input: n = 5 L[] = {1,5,9,13,21} R[] = {15,8,12,20,30} Output: 5 Explanation: The given ranges are [1,15] [5, 8] [9, 12] [13, 20] [21, 30]. The number that is most common or appears most times in the ranges is 5. Your Task: The task is to complete the function maxOccured() which returns the maximum occured integer in all ranges. Expected Time Complexity: O(n+maxx). Expected Auxiliary Space: O(maxx). -maxx is maximum element in R[] Constraints: 1 ≤ n ≤ 106 0 ≤ L[i], R[i] ≤ 106 0 sayrash191 week ago int maxOccured(int l[], int r[], int n, int maxx){ // Your code here int a[maxx+2] = {0}; for(int i=0;i<n;i++) { a[l[i]] += 1; a[r[i]+1] -= 1; } int mx = a[0], index = 0; for(int i=1; i<maxx+1;i++) { a[i] += a[i-1]; if(mx < a[i]) { mx = a[i]; index = i; } } return index; }}; 0 venkata ramana s2 weeks ago There is a problem in dynamic allocation for each test call. Static allocation of temporary buffer solved the issue. Its more of an issue at the server side. Global static allocation is not a good idea. 0 venkata ramana s2 weeks ago Abort signal from abort(3) (SIGABRT) 0 nihal_singh1844 weeks ago int maxOccured(int L[], int R[], int n, int maxx){ maxx=1000; int harr[maxx]={0}; for(int i=0;i<n;i++){ harr[L[i]]++; harr[R[i]+1]--; } int max=0,res=0; for(int i=1;i<maxx;i++){ harr[i]+=harr[i-1]; if(max<harr[i]){ max=harr[i]; res=i; } } return res; } Why this solution shows SEG Fault? 0 fabriciopolicarpo0Premium1 month ago This is the only solution I managed to get that would actually pass all test cases class Solution: #Complete this function #Function to find the maximum occurred integer in all ranges. def maxOccured(self,L,R,N,maxx): # array to hold values largest = max(R) maxim = largest + 3 arr = [0 for i in range(maxim)] # we add 1 at range start and -1 at range end maximumIndex = -1 for i in range(0, N, 1): arr[L[i]] += 1 arr[R[i] + 1] -=1 if R[i] > maximumIndex: maximumIndex = R[i] # find the prefix sum and index # having max prefix sum largest = arr[0] idx = 0 for i in range(1, maximumIndex, 1): arr[i] += arr[i -1] if (largest < arr[i]): largest = arr[i] idx = i return idx 0 akasksingh0801 month ago java: class Solution{ //Function to find the maximum occurred integer in all ranges. public static int maxOccured(int L[], int R[], int n, int maxx){ int arr[]= new int [1000000]; for(int i=0; i<n; i++) { arr[L[i]]++; arr[R[i]+1]--; } int max = arr[0],res=0; for(int i=1;i<1000000;i++) { arr[i]=arr[i]+arr[i-1]; if(max<arr[i]) { max=arr[i]; res=i; } } return res; } } 0 dipanshusharma93131 month ago // java solution class Solution{ //Function to find the maximum occurred integer in all ranges. public static int maxOccured(int L[], int R[], int n, int maxx){ int arr[] = new int[1000000]; for(int i=0;i<n;i++){ int a = L[i]; int b = R[i]; while(a<=b){ arr[a]++; a++; } } int temp = arr[0]; int max = 0; for(int j=0;j<arr.length;j++){ if(arr[j]>temp){ temp = arr[j]; max = j; } } return max; }} 0 ashuharshit222 months ago public static int maxOccured(int L[], int R[], int n, int maxx){ int[] arr = new int[maxx+1]; for(int i = 0; i <= maxx; i++){ arr[i] = 0; } for(int i = 0; i < n; i++){ while(L[i] <= R[i]){ arr[L[i]] = arr[L[i]] + 1; L[i]++; } } int maxOccured = Integer.MIN_VALUE; int ind = 0; for(int i = 0; i <= maxx; i++){ if(maxOccured < arr[i]){ maxOccured = arr[i]; ind = i; } } return ind; } 0 himeshnishant12 months ago JAVA Solution. public static int maxOccured(int L[], int R[], int n, int maxx){ int size = Arrays.stream(R).max().getAsInt() + 1; int hash[] = new int[size]; Arrays.fill(hash, 0); for(int i = 0; i < n; i++){ for(int j = L[i]; j <= R[i]; j++){ hash[j]++; } } int loc = 0, max = Integer.MIN_VALUE; for(int i = 0; i < size; i++){ if(max < hash[i]){ max = hash[i]; loc = i; } } return loc; } 0 suyashnigam342 months ago int arr[maxx]={0}; if(L[0]==0 && L[1]==0 && R[0]==1 && R[1]==1) return 0; // memset(arr, 0, sizeof arr); int maxi=-1; for(int i=0; i<n; i++){ arr[L[i]]++; arr[R[i]+1]--; if(R[i]>maxi) maxi = R[i]; } int presum=arr[0], ind; for(int i=1; i<maxx; i++){ arr[i]+=arr[i-1]; if(presum<arr[i]){ presum=arr[i]; ind=i; } } return ind; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 539, "s": 238, "text": "Given n integer ranges, the task is to find the maximum occurring integer in these ranges. If more than one such integer exits, find the smallest one. The ranges are given as two arrays L[] and R[]. L[i] consists of starting point of range and R[i] consists of corresponding end point of the range. " }, { "code": null, "e": 778, "s": 539, "text": "For example consider the following ranges.\nL[] = {2, 1, 3}, R[] = {5, 3, 9)\nRanges represented by above arrays are.\n[2, 5] = {2, 3, 4, 5}\n[1, 3] = {1, 2, 3}\n[3, 9] = {3, 4, 5, 6, 7, 8, 9}\nThe maximum occurred integer in these ranges is 3." }, { "code": null, "e": 789, "s": 778, "text": "Example 1:" }, { "code": null, "e": 985, "s": 789, "text": "Input:\nn = 4\nL[] = {1,4,3,1}\nR[] = {15,8,5,4}\nOutput: 4\nExplanation: The given ranges are [1,15]\n [4, 8] [3, 5] [1, 4]. The number that \nis most common or appears most times in \nthe ranges is 4.\n" }, { "code": null, "e": 996, "s": 985, "text": "Example 2:" }, { "code": null, "e": 1215, "s": 996, "text": "Input:\nn = 5\nL[] = {1,5,9,13,21}\nR[] = {15,8,12,20,30}\nOutput: 5\nExplanation: The given ranges are \n[1,15] [5, 8] [9, 12] [13, 20] \n[21, 30]. The number that is most \ncommon or appears most times in \nthe ranges is 5.\n\n" }, { "code": null, "e": 1333, "s": 1215, "text": "Your Task:\nThe task is to complete the function maxOccured() which returns the maximum occured integer in all ranges." }, { "code": null, "e": 1437, "s": 1333, "text": "Expected Time Complexity: O(n+maxx).\nExpected Auxiliary Space: O(maxx).\n-maxx is maximum element in R[]" }, { "code": null, "e": 1484, "s": 1437, "text": "\nConstraints:\n1 ≤ n ≤ 106\n0 ≤ L[i], R[i] ≤ 106" }, { "code": null, "e": 1486, "s": 1484, "text": "0" }, { "code": null, "e": 1506, "s": 1486, "text": "sayrash191 week ago" }, { "code": null, "e": 1935, "s": 1506, "text": "int maxOccured(int l[], int r[], int n, int maxx){ // Your code here int a[maxx+2] = {0}; for(int i=0;i<n;i++) { a[l[i]] += 1; a[r[i]+1] -= 1; } int mx = a[0], index = 0; for(int i=1; i<maxx+1;i++) { a[i] += a[i-1]; if(mx < a[i]) { mx = a[i]; index = i; } } return index; }};" }, { "code": null, "e": 1937, "s": 1935, "text": "0" }, { "code": null, "e": 1965, "s": 1937, "text": "venkata ramana s2 weeks ago" }, { "code": null, "e": 2124, "s": 1965, "text": "There is a problem in dynamic allocation for each test call. Static allocation of temporary buffer solved the issue. Its more of an issue at the server side. " }, { "code": null, "e": 2170, "s": 2124, "text": "Global static allocation is not a good idea. " }, { "code": null, "e": 2172, "s": 2170, "text": "0" }, { "code": null, "e": 2200, "s": 2172, "text": "venkata ramana s2 weeks ago" }, { "code": null, "e": 2237, "s": 2200, "text": "Abort signal from abort(3) (SIGABRT)" }, { "code": null, "e": 2239, "s": 2237, "text": "0" }, { "code": null, "e": 2265, "s": 2239, "text": "nihal_singh1844 weeks ago" }, { "code": null, "e": 2678, "s": 2265, "text": "int maxOccured(int L[], int R[], int n, int maxx){\n maxx=1000;\n int harr[maxx]={0};\n for(int i=0;i<n;i++){\n harr[L[i]]++;\n harr[R[i]+1]--;\n }\n int max=0,res=0;\n for(int i=1;i<maxx;i++){\n harr[i]+=harr[i-1];\n if(max<harr[i]){\n max=harr[i];\n res=i;\n }\n }\n return res;\n }" }, { "code": null, "e": 2713, "s": 2678, "text": "Why this solution shows SEG Fault?" }, { "code": null, "e": 2715, "s": 2713, "text": "0" }, { "code": null, "e": 2752, "s": 2715, "text": "fabriciopolicarpo0Premium1 month ago" }, { "code": null, "e": 3707, "s": 2752, "text": "This is the only solution I managed to get that would actually pass all test cases\n\nclass Solution:\n #Complete this function\n #Function to find the maximum occurred integer in all ranges.\n def maxOccured(self,L,R,N,maxx):\n \n # array to hold values\n largest = max(R)\n maxim = largest + 3\n arr = [0 for i in range(maxim)]\n \n # we add 1 at range start and -1 at range end\n \n maximumIndex = -1\n for i in range(0, N, 1):\n arr[L[i]] += 1\n arr[R[i] + 1] -=1\n if R[i] > maximumIndex:\n maximumIndex = R[i]\n \n \n \n # find the prefix sum and index\n # having max prefix sum\n largest = arr[0]\n idx = 0\n for i in range(1, maximumIndex, 1):\n arr[i] += arr[i -1]\n if (largest < arr[i]):\n largest = arr[i]\n idx = i\n return idx" }, { "code": null, "e": 3709, "s": 3707, "text": "0" }, { "code": null, "e": 3734, "s": 3709, "text": "akasksingh0801 month ago" }, { "code": null, "e": 4287, "s": 3734, "text": "java:\n\nclass Solution{\n //Function to find the maximum occurred integer in all ranges.\n public static int maxOccured(int L[], int R[], int n, int maxx){\n \n \n int arr[]= new int [1000000];\n for(int i=0; i<n; i++)\n {\n arr[L[i]]++;\n arr[R[i]+1]--;\n \n }\n int max = arr[0],res=0;\n for(int i=1;i<1000000;i++)\n {\n arr[i]=arr[i]+arr[i-1];\n if(max<arr[i])\n {\n max=arr[i];\n res=i;\n }\n }\n return res;\n } \n}" }, { "code": null, "e": 4289, "s": 4287, "text": "0" }, { "code": null, "e": 4319, "s": 4289, "text": "dipanshusharma93131 month ago" }, { "code": null, "e": 4337, "s": 4319, "text": "// java solution " }, { "code": null, "e": 4899, "s": 4337, "text": "class Solution{ //Function to find the maximum occurred integer in all ranges. public static int maxOccured(int L[], int R[], int n, int maxx){ int arr[] = new int[1000000]; for(int i=0;i<n;i++){ int a = L[i]; int b = R[i]; while(a<=b){ arr[a]++; a++; } } int temp = arr[0]; int max = 0; for(int j=0;j<arr.length;j++){ if(arr[j]>temp){ temp = arr[j]; max = j; } } return max; }} " }, { "code": null, "e": 4901, "s": 4899, "text": "0" }, { "code": null, "e": 4927, "s": 4901, "text": "ashuharshit222 months ago" }, { "code": null, "e": 5110, "s": 4927, "text": " public static int maxOccured(int L[], int R[], int n, int maxx){ int[] arr = new int[maxx+1]; for(int i = 0; i <= maxx; i++){ arr[i] = 0; } " }, { "code": null, "e": 5503, "s": 5110, "text": " for(int i = 0; i < n; i++){ while(L[i] <= R[i]){ arr[L[i]] = arr[L[i]] + 1; L[i]++; } } int maxOccured = Integer.MIN_VALUE; int ind = 0; for(int i = 0; i <= maxx; i++){ if(maxOccured < arr[i]){ maxOccured = arr[i]; ind = i; } } return ind; }" }, { "code": null, "e": 5505, "s": 5503, "text": "0" }, { "code": null, "e": 5532, "s": 5505, "text": "himeshnishant12 months ago" }, { "code": null, "e": 5547, "s": 5532, "text": "JAVA Solution." }, { "code": null, "e": 6115, "s": 5547, "text": "public static int maxOccured(int L[], int R[], int n, int maxx){\n int size = Arrays.stream(R).max().getAsInt() + 1;\n int hash[] = new int[size];\n Arrays.fill(hash, 0);\n for(int i = 0; i < n; i++){\n for(int j = L[i]; j <= R[i]; j++){\n hash[j]++;\n }\n }\n \n int loc = 0, max = Integer.MIN_VALUE;\n for(int i = 0; i < size; i++){\n if(max < hash[i]){\n max = hash[i];\n loc = i;\n }\n }\n \n return loc;\n }\n " }, { "code": null, "e": 6117, "s": 6115, "text": "0" }, { "code": null, "e": 6143, "s": 6117, "text": "suyashnigam342 months ago" }, { "code": null, "e": 6624, "s": 6143, "text": " int arr[maxx]={0}; if(L[0]==0 && L[1]==0 && R[0]==1 && R[1]==1) return 0; // memset(arr, 0, sizeof arr); int maxi=-1; for(int i=0; i<n; i++){ arr[L[i]]++; arr[R[i]+1]--; if(R[i]>maxi) maxi = R[i]; } int presum=arr[0], ind; for(int i=1; i<maxx; i++){ arr[i]+=arr[i-1]; if(presum<arr[i]){ presum=arr[i]; ind=i; } } return ind;" }, { "code": null, "e": 6770, "s": 6624, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6806, "s": 6770, "text": " Login to access your submissions. " }, { "code": null, "e": 6816, "s": 6806, "text": "\nProblem\n" }, { "code": null, "e": 6826, "s": 6816, "text": "\nContest\n" }, { "code": null, "e": 6889, "s": 6826, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7037, "s": 6889, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7245, "s": 7037, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7351, "s": 7245, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword. In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: And a selection from the "Orders" table: The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column: The following SQL statement creates two aliases, one for the CustomerName column and one for the ContactName column. Note: It requires double quotation marks or square brackets if the alias name contains spaces: The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, City and Country): Note: To get the SQL statement above to work in MySQL use the following: Note: To get the SQL statement above to work in Oracle use the following: The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter): The following SQL statement is the same as above, but without aliases: Aliases can be useful when: There are more than one table involved in a query Functions are used in the query Column names are big or not very readable Two or more columns are combined together When displaying the Customers table, make an ALIAS of the PostalCode column, the column should be called Pno instead. SELECT CustomerName, Address, PostalCode FROM Customers; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 80, "s": 0, "text": "SQL aliases are used to give a table, or a column in a table, a temporary name." }, { "code": null, "e": 139, "s": 80, "text": "Aliases are often used to make column names more readable." }, { "code": null, "e": 192, "s": 139, "text": "An alias only exists for the duration of that query." }, { "code": null, "e": 233, "s": 192, "text": "An alias is created with the AS keyword." }, { "code": null, "e": 304, "s": 233, "text": "In this tutorial we will use the well-known Northwind sample database." }, { "code": null, "e": 353, "s": 304, "text": "Below is a selection from the \"Customers\" table:" }, { "code": null, "e": 394, "s": 353, "text": "And a selection from the \"Orders\" table:" }, { "code": null, "e": 511, "s": 394, "text": "The following SQL statement creates two aliases, one for the CustomerID \ncolumn and one for the CustomerName column:" }, { "code": null, "e": 725, "s": 511, "text": "The following SQL statement creates two aliases, one for the CustomerName \ncolumn and one for the ContactName column. Note: It requires \ndouble quotation marks or square brackets if the alias name contains spaces:" }, { "code": null, "e": 854, "s": 725, "text": "The following SQL statement creates an alias named \"Address\" that combine four columns (Address, PostalCode, \nCity and Country):" }, { "code": null, "e": 927, "s": 854, "text": "Note: To get the SQL statement above to work in MySQL use the following:" }, { "code": null, "e": 1001, "s": 927, "text": "Note: To get the SQL statement above to work in Oracle use the following:" }, { "code": null, "e": 1261, "s": 1001, "text": "The following SQL statement selects all the orders from the customer with \nCustomerID=4 (Around the Horn). We use the \"Customers\" and \"Orders\" tables, and \ngive them the table aliases of \"c\" and \"o\" respectively (Here we use \naliases to make the SQL shorter):" }, { "code": null, "e": 1332, "s": 1261, "text": "The following SQL statement is the same as above, but without aliases:" }, { "code": null, "e": 1360, "s": 1332, "text": "Aliases can be useful when:" }, { "code": null, "e": 1410, "s": 1360, "text": "There are more than one table involved in a query" }, { "code": null, "e": 1442, "s": 1410, "text": "Functions are used in the query" }, { "code": null, "e": 1484, "s": 1442, "text": "Column names are big or not very readable" }, { "code": null, "e": 1526, "s": 1484, "text": "Two or more columns are combined together" }, { "code": null, "e": 1644, "s": 1526, "text": "When displaying the Customers table,\nmake an ALIAS of the PostalCode column,\nthe column should be called Pno instead." }, { "code": null, "e": 1703, "s": 1644, "text": "SELECT CustomerName,\nAddress,\nPostalCode \nFROM Customers;\n" }, { "code": null, "e": 1722, "s": 1703, "text": "Start the Exercise" }, { "code": null, "e": 1755, "s": 1722, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1797, "s": 1755, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1904, "s": 1797, "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": 1923, "s": 1904, "text": "[email protected]" } ]
A financial neural network for quants | by Nicolus Rotich | Towards Data Science
Artificial intelligence (AI) is continuously becoming an integral part of what we do nowadays, from the suggestions of the YouTube videos we ought to watch, to the algorithms running our high frequency trading in the Wall Street. Indeed Google algorithms know what we prefer, better than what we want. That was according to the Twitter CEO and founder — Jack Dorsey. This would not be mentioned if it were not for pattern recognition and classification, which are the main underlying principles of AI. Although the two principles have been undertaken for centuries purely through conventional statistical inference and mathematics, it took us (as a civilization) a while to recognize these processes were not good enough, rather they can be incredibly difficult to solve, if not clumsy and time consuming to say the least. Artificial neural networks forms the core of AI, as they are the main entities that have been used to successfully mimic unnecessarily voluntary, but evidently the right decisions nevertheless in many instances. Here we are referring to autonomous or self-driving cars, speech and facial recognition, objects tracking, and even humanoid robots. As a result, there are many types of neural networks that have been put to use up to date for various purposes. For example: Feed forward neural networks, radial basis function neural nets, recurrent neural networks, convolutional neural networks, modular neural networks, and Kohonen self-organizing neural nets. The latter one is particularly dear to me, as professor Teuvo Kohonen — the proponent happens to be one of my biggest inspirational figures since I got to know about neural networks in general, and how they function. My first project on neural networks concerned prediction of wind speeds and directions as part of a feasibility study for setting up wind farms in various municipalities in Finland1. Even though the concept was advanced, the very basics such as types of neural networks and which ones suits what problem are discussed in this reference. This article is however not about the types of neural networks, but a particular one as the title suggests — financial neural network. You will notice it doesn’t appear in the types of neural nets listed above, and may not appear elsewhere at all at the moment. It is one of those patterns that we come across in the relatively new playground of AI. Imagine this scenario, supposing that the survivors of RMS titanic (April 1912) could be pre-determined and foretold? that means you will have to assume you already knew the accident would occur — that’s kinda creepy. Let’s make it even more interesting, what if the number of men, women, and children could be told a part, and classified according to the injuries they would sustain, just by the position they occupied in the cruise ship. This was an unfortunate incident — let’s consider asset trading. In a similar way, supposing that an asset that you are about to buy, say a stock, future, bonds, or even cryptocurrency could already be pre-determined in such a way that you could tell which trade will be profitable and which will not, even before you get into those trades. You would be more judicious in knowing what to trade right? This is what alpha-beta financial neural network is all about. With this type of neural network, you attempt to classify the trades you are about to enter, and assign a probability of whether it would be profitable and worthy to engage in or not. These are the decisions that usually determine the the “buy” and “sell” side signal of your strategy, in particular cases that you are writing a code for algorithmic trading. This class of neural network is a classifier, with the input being a ratio of the current highest closing rate, “High” and opening, “Open” rates ratio as a single input, and a bias of -1. These are passed through a logistic activation function that scales the input to a probability distribution function between 0 and 1. To perform an illustration on this: Let High be z, Open be x, and weights be w: The symbol β is the bias, and in this case is a negative constant -1. The activation function α is a function of the weights that are initialized in the beginning and estimated as the classification progresses. Gradient descent is the ultimate measure of the performance efficiency of the model. Minimizing the gradient is equivalent to increasing the value of the probability distribution function, and in the process we get the following: Following along always makes it tenable if you seriously want to consider using this type of technology as you code your next trading algorithm. We will begin by listing the requirements to enable you accomplish this task: First you need to acquaint yourself with using data frames in python. Next you will need python3.6 installed on your system. You also need to have pandas and numpy basics. Finally, this is not a must, but installing jupyter notebook or ipython will lessen your work to a large extent. We will make use on the standard asset information, presented in a table format with columns: ‘date’, ‘open’, ‘high’, ‘low’, ‘close’, ‘adj close’, ‘volume’. You can get this from yahoo finance, downloaded to your project folder. For this case study, we will make use of the ticker symbols ‘AAPL’ and ‘GOOG’, corresponding to historical stock data for Aple inc. and Google Inc. This will effectively download the data to your project. First, navigate to your project folder. This (the whole project rather) is best done when you can work on the command prompt, or Unix terminal. I will assume Linux terminal for this. Therefore ensure you have installed all the required software, and run the following commands to get started: $ cd /your/project/root/directory/$ jupyter notebook The above should bring up a text editor window within your browser, similar to this one: Click the red-circled area to create a new document where we will place our code. We will then proceed to import the libraries as mentioned earlier. These are: pandas, numpy, and time as follows: # import librariesimport pandas as pdimport numpy as npimport time# Read in the data from the downloaded csv file(s) into a data framedf = pd.read_csv('AAPL.csv') To check out the data imported to your workspace, type the following and run the cell — clicking the red-rectangular selection in Fig. 2: This will result in something like this: We wish to change the cases for the column names for simplicity in proceeding with the code. We therefore replace the existing by running the following code: df.columns = ['date', 'open', 'high', 'low', 'close', 'adjclose', 'volume'] You can do a whole lot of exercises here, for instance you can filter out only positive trades (pos) that you would have desired to enter — i.e. the trades that would have yielded profits had you entered into back then. To do this, simply key in the following code: pos = df[df['change'] > 0 ] You can do the same for the trades that ended up yielding negative results, or loses (neg). You might have desired either not to get involved in these trades, or only get in to buy — use them to create a buy signal. You would then key in: neg = df[df['change']< 0 ] This classifier uses the simplest indicators ever. These are: The ratio of closing to opening rates, which will be the input to the neural network, and We will also compute the change that we will use as a guide, more like control experiment. The corresponding code is therefore placed as follows: df['change'] = df['close'] - df['open']df['ind'] = (df['high']/df['open']) -1df.head() Above code will create two extra columns, one with the ratio as discussed — let’s call this ‘ind’, and the other simply call it ‘change’ as we have always known. Notice that the variable ‘ind’ is already mirroring the LHS of Eq. (1). We will now proceed to compute the RHS in the following sections. We will start by assigning a set of linear weights using numpy library as follows: w = np.linspace(-6,6,len(df)) The above code will define a linear set of parameters that will be used to compute the probability distribution function — or the activation function in Eq. (2). Alpha is then calculated as follows: alpha = 1/(1+np.exp(-w)) We are done. Now, we need to implement the actual equation in the data frame and check out the results. In the simplest terms, you will key in the following for every value of alpha that you compute from above. test = df[df['ind'] >= alpha]eval = test[test['change'] > 0 ] We have seen that it asset trading is not different from other phenomena where theoretical approaches for predictions exist. As such, asset trading can be classified based on their potential—rather, the trades themselves can be classified with the sole aim of deciding whether to enter or not. The key parameter is the projected state of profitability. The following code sums up all the steps outlined above: import pandas as pdimport numpy as npimport timefrom termcolor import colored# Read in the data from the csv filedf = pd.read_csv('AAPL.csv')# Reduce the column names to lower casedf.columns = ['date', 'open', 'high', 'low', 'close', 'adjclose', 'volume']# compute the change to use as a guide in backtestingdf['change'] = df['close'] - df['open']# populate the classifierdf['ind'] = (df['high']/df['open']) -1# Initialize the weightsparam = np.linspace(-6,6,len(df))# Fire the neural networketa = 0while eta < 100: for i in param: alpha = 1/(1+np.exp(-i)) test = df[df['ind'] >= alpha] if len(test) > 0: pos = test[test['change'] > 0] eta = len(pos)*100/len(test) #time.sleep(1) print(colored (i, 'green'), alpha, len(test), colored(eta, 'red')) else: passelse: print('done classifying') Once you have determined the minimum value of probability or alpha of trades to get into, the buy and sell signals can simply be written as: dataframe[dataframe['ind'] < min_alpha ] ----> buydataframe[dataframe['ind'] >= min_alpha ] ---> sell The resulting table is a standard output of the (longer) code above printed to your screen. Check out this scenario: Let’s suppose that the final weight, w you settle on is ‘-4.23’, the activation function, α would yield ‘0.0143’, and the probability is thus 0.90566 — marked in the figure 8. As seen on the table there are three columns first: the weights, second column: alpha value, third the efficiency of the model, and finally: the number of trades entered onto. This means that had you entered that trade, there is a 90.6% chance that you would have emerged with a profit, and conversely, a 9.4% chance that you would come out with a loss. As of how this percentage is calculated, we simply compute the length of the data frame with the variable ‘change’ greater than zero in the ‘eval’ data frame, and compare with the total length of the data frame ‘test’. Pros Alpha-Beta classifier is quite accurate — at least from back testing results. Theoretically, it can guarantee as high as 100% classification efficiency. The best feature however, is that the higher the model efficiency, meaning fewer trades, the higher not only the the reward, but also fewer chances to lose. Hence the feature acts like a stop loss of some kind. This implies that you can choose to get in to just a few trades but with high potential for profitability. On the other hand, you may choose to enter into many trades, each with little benefits. This will help you in diversifying the risk, rather than concentrating all in one place. Finally, alpha-beta classifier supports Do Not Repeat Yourself (DRY). One model may fit more than one situations. For instance, download Google Inc. historical data (saved as GOOG.csv), with everything else remaining the same, you should find that the model still works — sometimes even better. Cons However, one major setback is that the higher the model efficiency increases, the fewer the number of trades you get into. F1#Help This is a new concept that could prove helpful especially for quants who likes to experiment and build up on it. If you are such a person, using this as a starting point and need help, let me know and I will give as much support as possible. [1] Rotich, N.K., Backman, J., Linnanen, L. and Daniil, P., 2014. Wind resource assessment and forecast planning with neural networks. Journal of Sustainable Development of Energy, Water and Environment Systems, 2(2), pp.174–190.
[ { "code": null, "e": 673, "s": 171, "text": "Artificial intelligence (AI) is continuously becoming an integral part of what we do nowadays, from the suggestions of the YouTube videos we ought to watch, to the algorithms running our high frequency trading in the Wall Street. Indeed Google algorithms know what we prefer, better than what we want. That was according to the Twitter CEO and founder — Jack Dorsey. This would not be mentioned if it were not for pattern recognition and classification, which are the main underlying principles of AI." }, { "code": null, "e": 1339, "s": 673, "text": "Although the two principles have been undertaken for centuries purely through conventional statistical inference and mathematics, it took us (as a civilization) a while to recognize these processes were not good enough, rather they can be incredibly difficult to solve, if not clumsy and time consuming to say the least. Artificial neural networks forms the core of AI, as they are the main entities that have been used to successfully mimic unnecessarily voluntary, but evidently the right decisions nevertheless in many instances. Here we are referring to autonomous or self-driving cars, speech and facial recognition, objects tracking, and even humanoid robots." }, { "code": null, "e": 2557, "s": 1339, "text": "As a result, there are many types of neural networks that have been put to use up to date for various purposes. For example: Feed forward neural networks, radial basis function neural nets, recurrent neural networks, convolutional neural networks, modular neural networks, and Kohonen self-organizing neural nets. The latter one is particularly dear to me, as professor Teuvo Kohonen — the proponent happens to be one of my biggest inspirational figures since I got to know about neural networks in general, and how they function. My first project on neural networks concerned prediction of wind speeds and directions as part of a feasibility study for setting up wind farms in various municipalities in Finland1. Even though the concept was advanced, the very basics such as types of neural networks and which ones suits what problem are discussed in this reference. This article is however not about the types of neural networks, but a particular one as the title suggests — financial neural network. You will notice it doesn’t appear in the types of neural nets listed above, and may not appear elsewhere at all at the moment. It is one of those patterns that we come across in the relatively new playground of AI." }, { "code": null, "e": 3062, "s": 2557, "text": "Imagine this scenario, supposing that the survivors of RMS titanic (April 1912) could be pre-determined and foretold? that means you will have to assume you already knew the accident would occur — that’s kinda creepy. Let’s make it even more interesting, what if the number of men, women, and children could be told a part, and classified according to the injuries they would sustain, just by the position they occupied in the cruise ship. This was an unfortunate incident — let’s consider asset trading." }, { "code": null, "e": 3820, "s": 3062, "text": "In a similar way, supposing that an asset that you are about to buy, say a stock, future, bonds, or even cryptocurrency could already be pre-determined in such a way that you could tell which trade will be profitable and which will not, even before you get into those trades. You would be more judicious in knowing what to trade right? This is what alpha-beta financial neural network is all about. With this type of neural network, you attempt to classify the trades you are about to enter, and assign a probability of whether it would be profitable and worthy to engage in or not. These are the decisions that usually determine the the “buy” and “sell” side signal of your strategy, in particular cases that you are writing a code for algorithmic trading." }, { "code": null, "e": 4178, "s": 3820, "text": "This class of neural network is a classifier, with the input being a ratio of the current highest closing rate, “High” and opening, “Open” rates ratio as a single input, and a bias of -1. These are passed through a logistic activation function that scales the input to a probability distribution function between 0 and 1. To perform an illustration on this:" }, { "code": null, "e": 4222, "s": 4178, "text": "Let High be z, Open be x, and weights be w:" }, { "code": null, "e": 4663, "s": 4222, "text": "The symbol β is the bias, and in this case is a negative constant -1. The activation function α is a function of the weights that are initialized in the beginning and estimated as the classification progresses. Gradient descent is the ultimate measure of the performance efficiency of the model. Minimizing the gradient is equivalent to increasing the value of the probability distribution function, and in the process we get the following:" }, { "code": null, "e": 4886, "s": 4663, "text": "Following along always makes it tenable if you seriously want to consider using this type of technology as you code your next trading algorithm. We will begin by listing the requirements to enable you accomplish this task:" }, { "code": null, "e": 4956, "s": 4886, "text": "First you need to acquaint yourself with using data frames in python." }, { "code": null, "e": 5058, "s": 4956, "text": "Next you will need python3.6 installed on your system. You also need to have pandas and numpy basics." }, { "code": null, "e": 5171, "s": 5058, "text": "Finally, this is not a must, but installing jupyter notebook or ipython will lessen your work to a large extent." }, { "code": null, "e": 5605, "s": 5171, "text": "We will make use on the standard asset information, presented in a table format with columns: ‘date’, ‘open’, ‘high’, ‘low’, ‘close’, ‘adj close’, ‘volume’. You can get this from yahoo finance, downloaded to your project folder. For this case study, we will make use of the ticker symbols ‘AAPL’ and ‘GOOG’, corresponding to historical stock data for Aple inc. and Google Inc. This will effectively download the data to your project." }, { "code": null, "e": 5898, "s": 5605, "text": "First, navigate to your project folder. This (the whole project rather) is best done when you can work on the command prompt, or Unix terminal. I will assume Linux terminal for this. Therefore ensure you have installed all the required software, and run the following commands to get started:" }, { "code": null, "e": 5952, "s": 5898, "text": "$ cd /your/project/root/directory/$ jupyter notebook " }, { "code": null, "e": 6041, "s": 5952, "text": "The above should bring up a text editor window within your browser, similar to this one:" }, { "code": null, "e": 6237, "s": 6041, "text": "Click the red-circled area to create a new document where we will place our code. We will then proceed to import the libraries as mentioned earlier. These are: pandas, numpy, and time as follows:" }, { "code": null, "e": 6400, "s": 6237, "text": "# import librariesimport pandas as pdimport numpy as npimport time# Read in the data from the downloaded csv file(s) into a data framedf = pd.read_csv('AAPL.csv')" }, { "code": null, "e": 6538, "s": 6400, "text": "To check out the data imported to your workspace, type the following and run the cell — clicking the red-rectangular selection in Fig. 2:" }, { "code": null, "e": 6579, "s": 6538, "text": "This will result in something like this:" }, { "code": null, "e": 6737, "s": 6579, "text": "We wish to change the cases for the column names for simplicity in proceeding with the code. We therefore replace the existing by running the following code:" }, { "code": null, "e": 6813, "s": 6737, "text": "df.columns = ['date', 'open', 'high', 'low', 'close', 'adjclose', 'volume']" }, { "code": null, "e": 7079, "s": 6813, "text": "You can do a whole lot of exercises here, for instance you can filter out only positive trades (pos) that you would have desired to enter — i.e. the trades that would have yielded profits had you entered into back then. To do this, simply key in the following code:" }, { "code": null, "e": 7107, "s": 7079, "text": "pos = df[df['change'] > 0 ]" }, { "code": null, "e": 7346, "s": 7107, "text": "You can do the same for the trades that ended up yielding negative results, or loses (neg). You might have desired either not to get involved in these trades, or only get in to buy — use them to create a buy signal. You would then key in:" }, { "code": null, "e": 7373, "s": 7346, "text": "neg = df[df['change']< 0 ]" }, { "code": null, "e": 7435, "s": 7373, "text": "This classifier uses the simplest indicators ever. These are:" }, { "code": null, "e": 7525, "s": 7435, "text": "The ratio of closing to opening rates, which will be the input to the neural network, and" }, { "code": null, "e": 7671, "s": 7525, "text": "We will also compute the change that we will use as a guide, more like control experiment. The corresponding code is therefore placed as follows:" }, { "code": null, "e": 7758, "s": 7671, "text": "df['change'] = df['close'] - df['open']df['ind'] = (df['high']/df['open']) -1df.head()" }, { "code": null, "e": 8058, "s": 7758, "text": "Above code will create two extra columns, one with the ratio as discussed — let’s call this ‘ind’, and the other simply call it ‘change’ as we have always known. Notice that the variable ‘ind’ is already mirroring the LHS of Eq. (1). We will now proceed to compute the RHS in the following sections." }, { "code": null, "e": 8141, "s": 8058, "text": "We will start by assigning a set of linear weights using numpy library as follows:" }, { "code": null, "e": 8171, "s": 8141, "text": "w = np.linspace(-6,6,len(df))" }, { "code": null, "e": 8370, "s": 8171, "text": "The above code will define a linear set of parameters that will be used to compute the probability distribution function — or the activation function in Eq. (2). Alpha is then calculated as follows:" }, { "code": null, "e": 8395, "s": 8370, "text": "alpha = 1/(1+np.exp(-w))" }, { "code": null, "e": 8606, "s": 8395, "text": "We are done. Now, we need to implement the actual equation in the data frame and check out the results. In the simplest terms, you will key in the following for every value of alpha that you compute from above." }, { "code": null, "e": 8668, "s": 8606, "text": "test = df[df['ind'] >= alpha]eval = test[test['change'] > 0 ]" }, { "code": null, "e": 9078, "s": 8668, "text": "We have seen that it asset trading is not different from other phenomena where theoretical approaches for predictions exist. As such, asset trading can be classified based on their potential—rather, the trades themselves can be classified with the sole aim of deciding whether to enter or not. The key parameter is the projected state of profitability. The following code sums up all the steps outlined above:" }, { "code": null, "e": 9956, "s": 9078, "text": "import pandas as pdimport numpy as npimport timefrom termcolor import colored# Read in the data from the csv filedf = pd.read_csv('AAPL.csv')# Reduce the column names to lower casedf.columns = ['date', 'open', 'high', 'low', 'close', 'adjclose', 'volume']# compute the change to use as a guide in backtestingdf['change'] = df['close'] - df['open']# populate the classifierdf['ind'] = (df['high']/df['open']) -1# Initialize the weightsparam = np.linspace(-6,6,len(df))# Fire the neural networketa = 0while eta < 100: for i in param: alpha = 1/(1+np.exp(-i)) test = df[df['ind'] >= alpha] if len(test) > 0: pos = test[test['change'] > 0] eta = len(pos)*100/len(test) #time.sleep(1) print(colored (i, 'green'), alpha, len(test), colored(eta, 'red')) else: passelse: print('done classifying')" }, { "code": null, "e": 10097, "s": 9956, "text": "Once you have determined the minimum value of probability or alpha of trades to get into, the buy and sell signals can simply be written as:" }, { "code": null, "e": 10199, "s": 10097, "text": "dataframe[dataframe['ind'] < min_alpha ] ----> buydataframe[dataframe['ind'] >= min_alpha ] ---> sell" }, { "code": null, "e": 10316, "s": 10199, "text": "The resulting table is a standard output of the (longer) code above printed to your screen. Check out this scenario:" }, { "code": null, "e": 10668, "s": 10316, "text": "Let’s suppose that the final weight, w you settle on is ‘-4.23’, the activation function, α would yield ‘0.0143’, and the probability is thus 0.90566 — marked in the figure 8. As seen on the table there are three columns first: the weights, second column: alpha value, third the efficiency of the model, and finally: the number of trades entered onto." }, { "code": null, "e": 11065, "s": 10668, "text": "This means that had you entered that trade, there is a 90.6% chance that you would have emerged with a profit, and conversely, a 9.4% chance that you would come out with a loss. As of how this percentage is calculated, we simply compute the length of the data frame with the variable ‘change’ greater than zero in the ‘eval’ data frame, and compare with the total length of the data frame ‘test’." }, { "code": null, "e": 11070, "s": 11065, "text": "Pros" }, { "code": null, "e": 11148, "s": 11070, "text": "Alpha-Beta classifier is quite accurate — at least from back testing results." }, { "code": null, "e": 11223, "s": 11148, "text": "Theoretically, it can guarantee as high as 100% classification efficiency." }, { "code": null, "e": 11718, "s": 11223, "text": "The best feature however, is that the higher the model efficiency, meaning fewer trades, the higher not only the the reward, but also fewer chances to lose. Hence the feature acts like a stop loss of some kind. This implies that you can choose to get in to just a few trades but with high potential for profitability. On the other hand, you may choose to enter into many trades, each with little benefits. This will help you in diversifying the risk, rather than concentrating all in one place." }, { "code": null, "e": 12013, "s": 11718, "text": "Finally, alpha-beta classifier supports Do Not Repeat Yourself (DRY). One model may fit more than one situations. For instance, download Google Inc. historical data (saved as GOOG.csv), with everything else remaining the same, you should find that the model still works — sometimes even better." }, { "code": null, "e": 12018, "s": 12013, "text": "Cons" }, { "code": null, "e": 12141, "s": 12018, "text": "However, one major setback is that the higher the model efficiency increases, the fewer the number of trades you get into." }, { "code": null, "e": 12149, "s": 12141, "text": "F1#Help" }, { "code": null, "e": 12391, "s": 12149, "text": "This is a new concept that could prove helpful especially for quants who likes to experiment and build up on it. If you are such a person, using this as a starting point and need help, let me know and I will give as much support as possible." } ]
Hotel Management System
10 Feb, 2022 Given the data for Hotel management and User:Hotel Data: Hotel Name Room Available Location Rating Price per Room H1 4 Bangalore 5 100 H2 5 Bangalore 5 200 H3 6 Mumbai 3 100 User Data: User Name UserID Booking Cost U1 2 1000 U2 3 1200 U3 4 1100 The task is to answer the following question. Print the hotel data.Sort hotels by Name.Sort Hotel by highest rating.Print Hotel data for Bangalore Location.Sort hotels by maximum number of rooms Available.Print user Booking data. Print the hotel data. Sort hotels by Name. Sort Hotel by highest rating. Print Hotel data for Bangalore Location. Sort hotels by maximum number of rooms Available. Print user Booking data. Machine coding round involves solving a design problem in a matter of a couple of hours. It requires designing and coding a clean, modular and extensible solution based on a specific set of requirements. Approach: Create classes for Hotel data and User data. Initialize variables that stores Hotel data and User data. Create Objects for Hotel and user classes that access the Hotel data and User data. initialize two vector array that holds the hotel data and user data. solve the Above questions one by one. Below is the implementation of the above approach. C++ Python3 // C++ program to solve// the given question #include <algorithm>#include <iostream>#include <string>#include <vector> using namespace std; // Create class for hotel data.class Hotel {public: string name; int roomAvl; string location; int rating; int pricePr;}; // Create class for user data.class User : public Hotel {public: string uname; int uId; int cost;}; // Function to Sort Hotels by// Bangalore locationbool sortByBan(Hotel& A, Hotel& B){ return A.name > B.name;} // Function to sort hotels// by rating.bool sortByr(Hotel& A, Hotel& B){ return A.rating > B.rating;} // Function to sort hotels// by rooms availability.bool sortByRoomAvailable(Hotel& A, Hotel& B){ return A.roomAvl < B.roomAvl;} // Print hotels data.void PrintHotelData(vector<Hotel> hotels){ cout << "PRINT HOTELS DATA:" << endl; cout << "HotelName" << " " << "Room Available" << " " << "Location" << " " << "Rating" << " " << "PricePer Room:" << endl; for (int i = 0; i < 3; i++) { cout << hotels[i].name << " " << hotels[i].roomAvl << " " << hotels[i].location << " " << hotels[i].rating << " " << hotels[i].pricePr << endl; } cout << endl;} // Sort Hotels data by name.void SortHotelByName(vector<Hotel> hotels){ cout << "SORT BY NAME:" << endl; std::sort(hotels.begin(), hotels.end(), sortByBan); for (int i = 0; i < hotels.size(); i++) { cout << hotels[i].name << " " << hotels[i].roomAvl << " " << hotels[i].location << " " << hotels[i].rating << " " << " " << hotels[i].pricePr << endl; } cout << endl;} // Sort Hotels by ratingvoid SortHotelByRating(vector<Hotel> hotels){ cout << "SORT BY A RATING:" << endl; std::sort(hotels.begin(), hotels.end(), sortByr); for (int i = 0; i < hotels.size(); i++) { cout << hotels[i].name << " " << hotels[i].roomAvl << " " << hotels[i].location << " " << hotels[i].rating << " " << " " << hotels[i].pricePr << endl; } cout << endl;} // Print Hotels for any city Location.void PrintHotelBycity(string s, vector<Hotel> hotels){ cout << "HOTELS FOR " << s << " LOCATION IS:" << endl; for (int i = 0; i < hotels.size(); i++) { if (hotels[i].location == s) { cout << hotels[i].name << " " << hotels[i].roomAvl << " " << hotels[i].location << " " << hotels[i].rating << " " << " " << hotels[i].pricePr << endl; } } cout << endl;} // Sort hotels by room Available.void SortByRoomAvailable(vector<Hotel> hotels){ cout << "SORT BY ROOM AVAILABLE:" << endl; std::sort(hotels.begin(), hotels.end(), sortByRoomAvailable); for (int i = hotels.size() - 1; i >= 0; i--) { cout << hotels[i].name << " " << hotels[i].roomAvl << " " << hotels[i].location << " " << hotels[i].rating << " " << " " << hotels[i].pricePr << endl; } cout << endl;} // Print the user's datavoid PrintUserData(string userName[], int userId[], int bookingCost[], vector<Hotel> hotels){ vector<User> user; User u; // Access user data. for (int i = 0; i < 3; i++) { u.uname = userName[i]; u.uId = userId[i]; u.cost = bookingCost[i]; user.push_back(u); } // Print User data. cout << "PRINT USER BOOKING DATA:" << endl; cout << "UserName" << " " << "UserID" << " " << "HotelName" << " " << "BookingCost" << endl; for (int i = 0; i < user.size(); i++) { cout << user[i].uname << " " << user[i].uId << " " << hotels[i].name << " " << user[i].cost << endl; }} // Functiont to solve// Hotel Management problemvoid HotelManagement(string userName[], int userId[], string hotelName[], int bookingCost[], int rooms[], string locations[], int ratings[], int prices[]){ // Initialize arrays that stores // hotel data and user data vector<Hotel> hotels; // Create Objects for // hotel and user. Hotel h; // Initialise the data for (int i = 0; i < 3; i++) { h.name = hotelName[i]; h.roomAvl = rooms[i]; h.location = locations[i]; h.rating = ratings[i]; h.pricePr = prices[i]; hotels.push_back(h); } cout << endl; // Call the various operations PrintHotelData(hotels); SortHotelByName(hotels); SortHotelByRating(hotels); PrintHotelBycity("Bangalore", hotels); SortByRoomAvailable(hotels); PrintUserData(userName, userId, bookingCost, hotels);} // Driver Code.int main(){ // Initialize variables to stores // hotels data and user data. string userName[] = { "U1", "U2", "U3" }; int userId[] = { 2, 3, 4 }; string hotelName[] = { "H1", "H2", "H3" }; int bookingCost[] = { 1000, 1200, 1100 }; int rooms[] = { 4, 5, 6 }; string locations[] = { "Bangalore", "Bangalore", "Mumbai" }; int ratings[] = { 5, 5, 3 }; int prices[] = { 100, 200, 100 }; // Function to perform operations HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices); return 0;} # Python program to solve# the given question # Create class for hotel data.class Hotel : sortParam='name' def __init__(self) -> None: self.name='' self.roomAvl=0 self.location='' self.rating=int self.pricePr=0 def __lt__(self,other): getattr(self,Hotel.sortParam)<getattr(other,Hotel.sortParam) # Function to change sort parameter to # name @classmethod def sortByName(cls): cls.sortParam='name' # Function to change sort parameter to # rating. @classmethod def sortByRate(cls): cls.sortParam='rating' # Function to change sort parameter to # room availability. @classmethod def sortByRoomAvailable(cls) : cls.sortParam='roomAvl' def __repr__(self) -> str: return "PRHOTELS DATA:\nHotelName:{}\tRoom Available:{}\tLocation:{}\tRating:{}\tPricePer Room:{}".format(self.name,self.roomAvl,self.location,self.rating,self.pricePr) # Create class for user data.class User: def __init__(self) -> None: self.uname='' self.uId=0 self.cost=0 def __repr__(self) -> str: return "UserName:{}\tUserId:{}\tBooking Cost:{}".format(self.uname,self.uId,self.cost) # Print hotels data.def PrintHotelData(hotels): for h in hotels: print(h) # Sort Hotels data by name.def SortHotelByName(hotels): print("SORT BY NAME:") Hotel.sortByName() hotels.sort() PrintHotelData(hotels) print() # Sort Hotels by ratingdef SortHotelByRating(hotels): print("SORT BY A RATING:") Hotel.sortByRate() hotels.sort() PrintHotelData(hotels) print() # Print Hotels for any city Location.def PrintHotelBycity(s,hotels): print("HOTELS FOR {} LOCATION ARE:".format(s)) hotelsByLoc=[h for h in hotels if h.location==s] PrintHotelData(hotelsByLoc) print() # Sort hotels by room Available.def SortByRoomAvailable(hotels): print("SORT BY ROOM AVAILABLE:") Hotel.sortByRoomAvailable() hotels.sort() PrintHotelData(hotels) print() # Print the user's datadef PrintUserData(userName, userId, bookingCost, hotels): users=[] # Access user data. for i in range(3) : u=User() u.uname = userName[i] u.uId = userId[i] u.cost = bookingCost[i] users.append(u) for i in range(len(users)) : print(users[i],"\tHotel name:",hotels[i].name) # Functiont to solve# Hotel Management problemdef HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices): # Initialize arrays that stores # hotel data and user data hotels=[] # Create Objects for # hotel and user. # Initialise the data for i in range(3) : h=Hotel() h.name = hotelName[i] h.roomAvl = rooms[i] h.location = locations[i] h.rating = ratings[i] h.pricePr = prices[i] hotels.append(h) print() # Call the various operations PrintHotelData(hotels) SortHotelByName(hotels) SortHotelByRating(hotels) PrintHotelBycity("Bangalore", hotels) SortByRoomAvailable(hotels) PrintUserData(userName, userId, bookingCost, hotels) # Driver Code.if __name__ == '__main__': # Initialize variables to stores # hotels data and user data. userName = ["U1", "U2", "U3"] userId = [2, 3, 4] hotelName = ["H1", "H2", "H3"] bookingCost = [1000, 1200, 1100] rooms = [4, 5, 6] locations = ["Bangalore", "Bangalore", "Mumbai"] ratings = [5, 5, 3] prices = [100, 200, 100] # Function to perform operations HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices) PRINT HOTELS DATA: HotelName Room Available Location Rating PricePer Room: H1 4 Bangalore 5 100 H2 5 Bangalore 5 200 H3 6 Mumbai 3 100 SORT BY NAME: H3 6 Mumbai 3 100 H2 5 Bangalore 5 200 H1 4 Bangalore 5 100 SORT BY A RATING: H1 4 Bangalore 5 100 H2 5 Bangalore 5 200 H3 6 Mumbai 3 100 HOTELS FOR Bangalore LOCATION IS: H1 4 Bangalore 5 100 H2 5 Bangalore 5 200 SORT BY ROOM AVAILABLE: H3 6 Mumbai 3 100 H2 5 Bangalore 5 200 H1 4 Bangalore 5 100 PRINT USER BOOKING DATA: UserName UserID HotelName BookingCost U1 2 H1 1000 U2 3 H2 1200 U3 4 H3 1100 saurabh1990aror surindertarika1234 amartyaghoshgfg surinderdawra388 simmytarika5 Algorithms CS - Placements Placements Project Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2022" }, { "code": null, "e": 86, "s": 28, "text": "Given the data for Hotel management and User:Hotel Data: " }, { "code": null, "e": 355, "s": 86, "text": "Hotel Name Room Available Location Rating Price per Room\nH1 4 Bangalore 5 100\nH2 5 Bangalore 5 200\nH3 6 Mumbai 3 100" }, { "code": null, "e": 367, "s": 355, "text": "User Data: " }, { "code": null, "e": 546, "s": 367, "text": "User Name UserID Booking Cost\nU1 2 1000\nU2 3 1200\nU3 4 1100" }, { "code": null, "e": 592, "s": 546, "text": "The task is to answer the following question." }, { "code": null, "e": 776, "s": 592, "text": "Print the hotel data.Sort hotels by Name.Sort Hotel by highest rating.Print Hotel data for Bangalore Location.Sort hotels by maximum number of rooms Available.Print user Booking data." }, { "code": null, "e": 798, "s": 776, "text": "Print the hotel data." }, { "code": null, "e": 819, "s": 798, "text": "Sort hotels by Name." }, { "code": null, "e": 849, "s": 819, "text": "Sort Hotel by highest rating." }, { "code": null, "e": 890, "s": 849, "text": "Print Hotel data for Bangalore Location." }, { "code": null, "e": 940, "s": 890, "text": "Sort hotels by maximum number of rooms Available." }, { "code": null, "e": 965, "s": 940, "text": "Print user Booking data." }, { "code": null, "e": 1171, "s": 965, "text": "Machine coding round involves solving a design problem in a matter of a couple of hours. It requires designing and coding a clean, modular and extensible solution based on a specific set of requirements. " }, { "code": null, "e": 1183, "s": 1171, "text": "Approach: " }, { "code": null, "e": 1228, "s": 1183, "text": "Create classes for Hotel data and User data." }, { "code": null, "e": 1287, "s": 1228, "text": "Initialize variables that stores Hotel data and User data." }, { "code": null, "e": 1371, "s": 1287, "text": "Create Objects for Hotel and user classes that access the Hotel data and User data." }, { "code": null, "e": 1440, "s": 1371, "text": "initialize two vector array that holds the hotel data and user data." }, { "code": null, "e": 1478, "s": 1440, "text": "solve the Above questions one by one." }, { "code": null, "e": 1530, "s": 1478, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1534, "s": 1530, "text": "C++" }, { "code": null, "e": 1542, "s": 1534, "text": "Python3" }, { "code": "// C++ program to solve// the given question #include <algorithm>#include <iostream>#include <string>#include <vector> using namespace std; // Create class for hotel data.class Hotel {public: string name; int roomAvl; string location; int rating; int pricePr;}; // Create class for user data.class User : public Hotel {public: string uname; int uId; int cost;}; // Function to Sort Hotels by// Bangalore locationbool sortByBan(Hotel& A, Hotel& B){ return A.name > B.name;} // Function to sort hotels// by rating.bool sortByr(Hotel& A, Hotel& B){ return A.rating > B.rating;} // Function to sort hotels// by rooms availability.bool sortByRoomAvailable(Hotel& A, Hotel& B){ return A.roomAvl < B.roomAvl;} // Print hotels data.void PrintHotelData(vector<Hotel> hotels){ cout << \"PRINT HOTELS DATA:\" << endl; cout << \"HotelName\" << \" \" << \"Room Available\" << \" \" << \"Location\" << \" \" << \"Rating\" << \" \" << \"PricePer Room:\" << endl; for (int i = 0; i < 3; i++) { cout << hotels[i].name << \" \" << hotels[i].roomAvl << \" \" << hotels[i].location << \" \" << hotels[i].rating << \" \" << hotels[i].pricePr << endl; } cout << endl;} // Sort Hotels data by name.void SortHotelByName(vector<Hotel> hotels){ cout << \"SORT BY NAME:\" << endl; std::sort(hotels.begin(), hotels.end(), sortByBan); for (int i = 0; i < hotels.size(); i++) { cout << hotels[i].name << \" \" << hotels[i].roomAvl << \" \" << hotels[i].location << \" \" << hotels[i].rating << \" \" << \" \" << hotels[i].pricePr << endl; } cout << endl;} // Sort Hotels by ratingvoid SortHotelByRating(vector<Hotel> hotels){ cout << \"SORT BY A RATING:\" << endl; std::sort(hotels.begin(), hotels.end(), sortByr); for (int i = 0; i < hotels.size(); i++) { cout << hotels[i].name << \" \" << hotels[i].roomAvl << \" \" << hotels[i].location << \" \" << hotels[i].rating << \" \" << \" \" << hotels[i].pricePr << endl; } cout << endl;} // Print Hotels for any city Location.void PrintHotelBycity(string s, vector<Hotel> hotels){ cout << \"HOTELS FOR \" << s << \" LOCATION IS:\" << endl; for (int i = 0; i < hotels.size(); i++) { if (hotels[i].location == s) { cout << hotels[i].name << \" \" << hotels[i].roomAvl << \" \" << hotels[i].location << \" \" << hotels[i].rating << \" \" << \" \" << hotels[i].pricePr << endl; } } cout << endl;} // Sort hotels by room Available.void SortByRoomAvailable(vector<Hotel> hotels){ cout << \"SORT BY ROOM AVAILABLE:\" << endl; std::sort(hotels.begin(), hotels.end(), sortByRoomAvailable); for (int i = hotels.size() - 1; i >= 0; i--) { cout << hotels[i].name << \" \" << hotels[i].roomAvl << \" \" << hotels[i].location << \" \" << hotels[i].rating << \" \" << \" \" << hotels[i].pricePr << endl; } cout << endl;} // Print the user's datavoid PrintUserData(string userName[], int userId[], int bookingCost[], vector<Hotel> hotels){ vector<User> user; User u; // Access user data. for (int i = 0; i < 3; i++) { u.uname = userName[i]; u.uId = userId[i]; u.cost = bookingCost[i]; user.push_back(u); } // Print User data. cout << \"PRINT USER BOOKING DATA:\" << endl; cout << \"UserName\" << \" \" << \"UserID\" << \" \" << \"HotelName\" << \" \" << \"BookingCost\" << endl; for (int i = 0; i < user.size(); i++) { cout << user[i].uname << \" \" << user[i].uId << \" \" << hotels[i].name << \" \" << user[i].cost << endl; }} // Functiont to solve// Hotel Management problemvoid HotelManagement(string userName[], int userId[], string hotelName[], int bookingCost[], int rooms[], string locations[], int ratings[], int prices[]){ // Initialize arrays that stores // hotel data and user data vector<Hotel> hotels; // Create Objects for // hotel and user. Hotel h; // Initialise the data for (int i = 0; i < 3; i++) { h.name = hotelName[i]; h.roomAvl = rooms[i]; h.location = locations[i]; h.rating = ratings[i]; h.pricePr = prices[i]; hotels.push_back(h); } cout << endl; // Call the various operations PrintHotelData(hotels); SortHotelByName(hotels); SortHotelByRating(hotels); PrintHotelBycity(\"Bangalore\", hotels); SortByRoomAvailable(hotels); PrintUserData(userName, userId, bookingCost, hotels);} // Driver Code.int main(){ // Initialize variables to stores // hotels data and user data. string userName[] = { \"U1\", \"U2\", \"U3\" }; int userId[] = { 2, 3, 4 }; string hotelName[] = { \"H1\", \"H2\", \"H3\" }; int bookingCost[] = { 1000, 1200, 1100 }; int rooms[] = { 4, 5, 6 }; string locations[] = { \"Bangalore\", \"Bangalore\", \"Mumbai\" }; int ratings[] = { 5, 5, 3 }; int prices[] = { 100, 200, 100 }; // Function to perform operations HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices); return 0;}", "e": 7576, "s": 1542, "text": null }, { "code": "# Python program to solve# the given question # Create class for hotel data.class Hotel : sortParam='name' def __init__(self) -> None: self.name='' self.roomAvl=0 self.location='' self.rating=int self.pricePr=0 def __lt__(self,other): getattr(self,Hotel.sortParam)<getattr(other,Hotel.sortParam) # Function to change sort parameter to # name @classmethod def sortByName(cls): cls.sortParam='name' # Function to change sort parameter to # rating. @classmethod def sortByRate(cls): cls.sortParam='rating' # Function to change sort parameter to # room availability. @classmethod def sortByRoomAvailable(cls) : cls.sortParam='roomAvl' def __repr__(self) -> str: return \"PRHOTELS DATA:\\nHotelName:{}\\tRoom Available:{}\\tLocation:{}\\tRating:{}\\tPricePer Room:{}\".format(self.name,self.roomAvl,self.location,self.rating,self.pricePr) # Create class for user data.class User: def __init__(self) -> None: self.uname='' self.uId=0 self.cost=0 def __repr__(self) -> str: return \"UserName:{}\\tUserId:{}\\tBooking Cost:{}\".format(self.uname,self.uId,self.cost) # Print hotels data.def PrintHotelData(hotels): for h in hotels: print(h) # Sort Hotels data by name.def SortHotelByName(hotels): print(\"SORT BY NAME:\") Hotel.sortByName() hotels.sort() PrintHotelData(hotels) print() # Sort Hotels by ratingdef SortHotelByRating(hotels): print(\"SORT BY A RATING:\") Hotel.sortByRate() hotels.sort() PrintHotelData(hotels) print() # Print Hotels for any city Location.def PrintHotelBycity(s,hotels): print(\"HOTELS FOR {} LOCATION ARE:\".format(s)) hotelsByLoc=[h for h in hotels if h.location==s] PrintHotelData(hotelsByLoc) print() # Sort hotels by room Available.def SortByRoomAvailable(hotels): print(\"SORT BY ROOM AVAILABLE:\") Hotel.sortByRoomAvailable() hotels.sort() PrintHotelData(hotels) print() # Print the user's datadef PrintUserData(userName, userId, bookingCost, hotels): users=[] # Access user data. for i in range(3) : u=User() u.uname = userName[i] u.uId = userId[i] u.cost = bookingCost[i] users.append(u) for i in range(len(users)) : print(users[i],\"\\tHotel name:\",hotels[i].name) # Functiont to solve# Hotel Management problemdef HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices): # Initialize arrays that stores # hotel data and user data hotels=[] # Create Objects for # hotel and user. # Initialise the data for i in range(3) : h=Hotel() h.name = hotelName[i] h.roomAvl = rooms[i] h.location = locations[i] h.rating = ratings[i] h.pricePr = prices[i] hotels.append(h) print() # Call the various operations PrintHotelData(hotels) SortHotelByName(hotels) SortHotelByRating(hotels) PrintHotelBycity(\"Bangalore\", hotels) SortByRoomAvailable(hotels) PrintUserData(userName, userId, bookingCost, hotels) # Driver Code.if __name__ == '__main__': # Initialize variables to stores # hotels data and user data. userName = [\"U1\", \"U2\", \"U3\"] userId = [2, 3, 4] hotelName = [\"H1\", \"H2\", \"H3\"] bookingCost = [1000, 1200, 1100] rooms = [4, 5, 6] locations = [\"Bangalore\", \"Bangalore\", \"Mumbai\"] ratings = [5, 5, 3] prices = [100, 200, 100] # Function to perform operations HotelManagement(userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices)", "e": 11555, "s": 7576, "text": null }, { "code": null, "e": 12317, "s": 11555, "text": "PRINT HOTELS DATA:\nHotelName Room Available Location Rating PricePer Room:\nH1 4 Bangalore 5 100\nH2 5 Bangalore 5 200\nH3 6 Mumbai 3 100\n\nSORT BY NAME:\nH3 6 Mumbai 3 100\nH2 5 Bangalore 5 200\nH1 4 Bangalore 5 100\n\nSORT BY A RATING:\nH1 4 Bangalore 5 100\nH2 5 Bangalore 5 200\nH3 6 Mumbai 3 100\n\nHOTELS FOR Bangalore LOCATION IS:\nH1 4 Bangalore 5 100\nH2 5 Bangalore 5 200\n\nSORT BY ROOM AVAILABLE:\nH3 6 Mumbai 3 100\nH2 5 Bangalore 5 200\nH1 4 Bangalore 5 100\n\nPRINT USER BOOKING DATA:\nUserName UserID HotelName BookingCost\nU1 2 H1 1000\nU2 3 H2 1200\nU3 4 H3 1100" }, { "code": null, "e": 12333, "s": 12317, "text": "saurabh1990aror" }, { "code": null, "e": 12352, "s": 12333, "text": "surindertarika1234" }, { "code": null, "e": 12368, "s": 12352, "text": "amartyaghoshgfg" }, { "code": null, "e": 12385, "s": 12368, "text": "surinderdawra388" }, { "code": null, "e": 12398, "s": 12385, "text": "simmytarika5" }, { "code": null, "e": 12409, "s": 12398, "text": "Algorithms" }, { "code": null, "e": 12425, "s": 12409, "text": "CS - Placements" }, { "code": null, "e": 12436, "s": 12425, "text": "Placements" }, { "code": null, "e": 12444, "s": 12436, "text": "Project" }, { "code": null, "e": 12455, "s": 12444, "text": "Algorithms" } ]
Flatten A list of NumPy arrays
16 Sep, 2021 Prerequisite Differences between Flatten() and Ravel() Numpy Functions, numpy.ravel() in Python, In this article, we will see how we can flatten a list of numpy arrays. NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Flatten a list of NumPy array means to combine the multiple dimensional NumPy arrays into a single array or list, below is the example List of numpy array : [array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]])] Flatten numpy array : array([ 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654]) Method 1 Using numpy’s concatenate method Python3 # importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # concatenating all the numpy arrayflatten = np.concatenate(list_array) # printing the ravel flatten arrayprint(flatten.ravel()) Output : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Method 2 Using numpy’s flatten method Python3 # importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy arrayflatten = np.array(list_array).flatten() # printing the flatten arrayprint(flatten) Output : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Method 3 Using numpy’s ravel method Python3 # importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy array using ravel methodflatten = np.array(list_array).ravel() # printing the flatten arrayprint(flatten) Output : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Method 4 Using numpy’s reshape method Python3 # importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy array using reshape methodflatten = np.array(list_array).reshape(-1) # printing the flatten arrayprint(flatten) Output : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] kapoorsagar226 adnanirshad158 Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Sep, 2021" }, { "code": null, "e": 126, "s": 28, "text": "Prerequisite Differences between Flatten() and Ravel() Numpy Functions, numpy.ravel() in Python, " }, { "code": null, "e": 414, "s": 126, "text": "In this article, we will see how we can flatten a list of numpy arrays. NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays." }, { "code": null, "e": 550, "s": 414, "text": "Flatten a list of NumPy array means to combine the multiple dimensional NumPy arrays into a single array or list, below is the example " }, { "code": null, "e": 885, "s": 550, "text": "List of numpy array : [array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]])]" }, { "code": null, "e": 1074, "s": 885, "text": "Flatten numpy array : array([ 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654]) " }, { "code": null, "e": 1118, "s": 1074, "text": "Method 1 Using numpy’s concatenate method " }, { "code": null, "e": 1126, "s": 1118, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # concatenating all the numpy arrayflatten = np.concatenate(list_array) # printing the ravel flatten arrayprint(flatten.ravel())", "e": 1821, "s": 1126, "text": null }, { "code": null, "e": 1831, "s": 1821, "text": "Output : " }, { "code": null, "e": 1881, "s": 1831, "text": "[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]" }, { "code": null, "e": 1920, "s": 1881, "text": "Method 2 Using numpy’s flatten method " }, { "code": null, "e": 1928, "s": 1920, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy arrayflatten = np.array(list_array).flatten() # printing the flatten arrayprint(flatten)", "e": 2603, "s": 1928, "text": null }, { "code": null, "e": 2613, "s": 2603, "text": "Output : " }, { "code": null, "e": 2663, "s": 2613, "text": "[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]" }, { "code": null, "e": 2700, "s": 2663, "text": "Method 3 Using numpy’s ravel method " }, { "code": null, "e": 2708, "s": 2700, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy array using ravel methodflatten = np.array(list_array).ravel() # printing the flatten arrayprint(flatten)", "e": 3400, "s": 2708, "text": null }, { "code": null, "e": 3410, "s": 3400, "text": "Output : " }, { "code": null, "e": 3460, "s": 3410, "text": "[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]" }, { "code": null, "e": 3500, "s": 3460, "text": "Method 4 Using numpy’s reshape method " }, { "code": null, "e": 3508, "s": 3500, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # list of numpy arraylist_array = [np.array([[1]]), np.array([[2]]), np.array([[3]]), np.array([[4]]), np.array([[5]]), np.array([[6]]), np.array([[7]]), np.array([[8]]), np.array([[9]]), np.array([[10]]), np.array([[11]]), np.array([[12]]), np.array([[13]]), np.array([[14]]), np.array([[15]]), np.array([[16]])] # flatten the numpy array using reshape methodflatten = np.array(list_array).reshape(-1) # printing the flatten arrayprint(flatten)", "e": 4206, "s": 3508, "text": null }, { "code": null, "e": 4216, "s": 4206, "text": "Output : " }, { "code": null, "e": 4266, "s": 4216, "text": "[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]" }, { "code": null, "e": 4283, "s": 4268, "text": "kapoorsagar226" }, { "code": null, "e": 4298, "s": 4283, "text": "adnanirshad158" }, { "code": null, "e": 4329, "s": 4298, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 4342, "s": 4329, "text": "Python-numpy" }, { "code": null, "e": 4349, "s": 4342, "text": "Python" } ]
How to add Custom Fonts in Android
22 Aug, 2021 Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. There are majorly three methods to add custom fonts to text in Android Studio. The first two methods involve the use of the Typeface class while the last method is quite direct and easy. Follow the entire article to explore all the methods. In this method, we’ll first download the font’s ttf file from the internet and then use them as an asset or a resource to set the Typeface. You may find the downloadable fonts here. Here Dancing Script font is used. Once you download the fonts of your choice, unzip the folder and copy the font file. By creating a new Android resource directory: Step 1: In the project’s resource folder, create a new Android Resource Directory of Resource type: font and paste this ‘ttf’ file here. Note that while pasting it, keep in mind that a resource file’s name can consist of lower-case letters and underscores only, so refactor the file accordingly. Step 2: Create the layout in the XML files. Step 3: Now in the MainActivity(necessarily the Activity corresponding to the layout file where the TextView to be customised lies), set the typeface for that TextView.activity_main.xmlMainActivity.javaactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>MainActivity.javapackage com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = ResourcesCompat.getFont( this, R.font.dancing_script_bold); textView.setTypeface(typeface); }} activity_main.xml MainActivity.java <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> package com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = ResourcesCompat.getFont( this, R.font.dancing_script_bold); textView.setTypeface(typeface); }} Output: By creating a new asset folder: Step 1: Create a new asset folder(app/New/Folder/Asset folder) in Android Studio and paste the ‘ttf’ file of the font here. The picture on the left shows how to add the assets folder to the project whereas the picture on the right shows the added ‘ttf’ file to it. Step 2: While we keep the XML layout to be same as earlier, the Java code of the MainActivity is modified this way.MainActivity.javaMainActivity.javapackage com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import com.example.android.customfonts.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = Typeface.createFromAsset( getAssets(), "macondo_swash_caps_regular.ttf"); textView.setTypeface(typeface); }} MainActivity.java package com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import com.example.android.customfonts.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = Typeface.createFromAsset( getAssets(), "macondo_swash_caps_regular.ttf"); textView.setTypeface(typeface); }} Output: In this method we’ll create a separate java class dediacted to a particular font and use this class instead of the conventional TextView tag in the XML file. Step 1: Download the font of your choice and use either of the above two approaches to store it in the project. I have pasted my file in the assets folder. Step 2: Create a new Java file in the package. Preferably name it according to the font that you want to implement. Here we have created a file named CalligraffittiRegular. Step 3: Extend the following class in this Java file:androidx.appcompat.widget.AppCompatTextView androidx.appcompat.widget.AppCompatTextView Step 4: Complete the Java code by adding the required constructors. Step 5: Create a method in the class wherein the typeface for the font is set. Step 6: Call this method in each constructor. Refer to the following code for a better understanding.CalligraffittiRegular.javaCalligraffittiRegular.javapackage com.example.android.customfonts; import android.content.Context;import android.graphics.Typeface;import android.util.AttributeSet; public class CalligraffittiRegular extends androidx.appcompat.widget.AppCompatTextView { public CalligraffittiRegular(Context context) { super(context); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs) { super(context, attrs); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initTypeface(context); } private void initTypeface(Context context) { Typeface tf = Typeface.createFromAsset( context.getAssets(), "calligraffitti_regular.ttf"); this.setTypeface(tf); }} CalligraffittiRegular.java package com.example.android.customfonts; import android.content.Context;import android.graphics.Typeface;import android.util.AttributeSet; public class CalligraffittiRegular extends androidx.appcompat.widget.AppCompatTextView { public CalligraffittiRegular(Context context) { super(context); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs) { super(context, attrs); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initTypeface(context); } private void initTypeface(Context context) { Typeface tf = Typeface.createFromAsset( context.getAssets(), "calligraffitti_regular.ttf"); this.setTypeface(tf); }} Step 7: Now in your XML layout file, use this font class instead of of the conventional TextView tag.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.android.customfonts.CalligraffittiRegular android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.616" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.462"/> </androidx.constraintlayout.widget.ConstraintLayout> activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.android.customfonts.CalligraffittiRegular android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.616" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.462"/> </androidx.constraintlayout.widget.ConstraintLayout> Output: With Android 8.0 (API Level 26) a simpler method was introduced for using fonts as a resource in Android Studio. The android:fontFamily attribute of the TextView class is used to specify the font. Step 1: Go to the XML file and go to the Design view. Step 2: Click the TextView you want to change the font of. Step 3: In the search bar, search for fontFamily. Step 4: In the dropdown menu, you can check out the fonts available. In case you want to explore more, scroll down and click ‘More Fonts...‘. Step 5: A dialog box pops up. Choose a font of your choice, choose the style you like in the preview, and click OK. Step 6: This would create a downloadable font and add it automatically to your project.The following files automatically get added to your project: The following files automatically get added to your project: Step 7: Now the XML file will be look like:activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/aref_ruqaa" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/aref_ruqaa" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: ConclusionWhile the last method seems easy and time-saving, however, it bundles the extra files with the APK of the app which might increase its size. Though this also ensures that the fonts are present even when the app works offline. The first method results in a smaller sized APK but the user might need access to the internet while the processing of the app if some other already present app does not have the same font stored in its cache. sagartomar9927 android How To Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Permanently Disable Swap in Linux? How to Install Jupyter Notebook on MacOS? How to Import JSON Data into SQL Server? How to Install and Use NVM on Windows? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples For-each loop in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Aug, 2021" }, { "code": null, "e": 486, "s": 28, "text": "Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. There are majorly three methods to add custom fonts to text in Android Studio. The first two methods involve the use of the Typeface class while the last method is quite direct and easy. Follow the entire article to explore all the methods." }, { "code": null, "e": 787, "s": 486, "text": "In this method, we’ll first download the font’s ttf file from the internet and then use them as an asset or a resource to set the Typeface. You may find the downloadable fonts here. Here Dancing Script font is used. Once you download the fonts of your choice, unzip the folder and copy the font file." }, { "code": null, "e": 833, "s": 787, "text": "By creating a new Android resource directory:" }, { "code": null, "e": 1129, "s": 833, "text": "Step 1: In the project’s resource folder, create a new Android Resource Directory of Resource type: font and paste this ‘ttf’ file here. Note that while pasting it, keep in mind that a resource file’s name can consist of lower-case letters and underscores only, so refactor the file accordingly." }, { "code": null, "e": 1173, "s": 1129, "text": "Step 2: Create the layout in the XML files." }, { "code": null, "e": 2909, "s": 1173, "text": "Step 3: Now in the MainActivity(necessarily the Activity corresponding to the layout file where the TextView to be customised lies), set the typeface for that TextView.activity_main.xmlMainActivity.javaactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TextView android:id=\"@+id/textview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>MainActivity.javapackage com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = ResourcesCompat.getFont( this, R.font.dancing_script_bold); textView.setTypeface(typeface); }}" }, { "code": null, "e": 2927, "s": 2909, "text": "activity_main.xml" }, { "code": null, "e": 2945, "s": 2927, "text": "MainActivity.java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TextView android:id=\"@+id/textview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3784, "s": 2945, "text": null }, { "code": "package com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = ResourcesCompat.getFont( this, R.font.dancing_script_bold); textView.setTypeface(typeface); }}", "e": 4446, "s": 3784, "text": null }, { "code": null, "e": 4454, "s": 4446, "text": "Output:" }, { "code": null, "e": 4486, "s": 4454, "text": "By creating a new asset folder:" }, { "code": null, "e": 4751, "s": 4486, "text": "Step 1: Create a new asset folder(app/New/Folder/Asset folder) in Android Studio and paste the ‘ttf’ file of the font here. The picture on the left shows how to add the assets folder to the project whereas the picture on the right shows the added ‘ttf’ file to it." }, { "code": null, "e": 5617, "s": 4751, "text": "Step 2: While we keep the XML layout to be same as earlier, the Java code of the MainActivity is modified this way.MainActivity.javaMainActivity.javapackage com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import com.example.android.customfonts.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = Typeface.createFromAsset( getAssets(), \"macondo_swash_caps_regular.ttf\"); textView.setTypeface(typeface); }}" }, { "code": null, "e": 5635, "s": 5617, "text": "MainActivity.java" }, { "code": "package com.example.android.customfonts; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.res.ResourcesCompat;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import com.example.android.customfonts.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textview); Typeface typeface = Typeface.createFromAsset( getAssets(), \"macondo_swash_caps_regular.ttf\"); textView.setTypeface(typeface); }}", "e": 6352, "s": 5635, "text": null }, { "code": null, "e": 6360, "s": 6352, "text": "Output:" }, { "code": null, "e": 6518, "s": 6360, "text": "In this method we’ll create a separate java class dediacted to a particular font and use this class instead of the conventional TextView tag in the XML file." }, { "code": null, "e": 6674, "s": 6518, "text": "Step 1: Download the font of your choice and use either of the above two approaches to store it in the project. I have pasted my file in the assets folder." }, { "code": null, "e": 6847, "s": 6674, "text": "Step 2: Create a new Java file in the package. Preferably name it according to the font that you want to implement. Here we have created a file named CalligraffittiRegular." }, { "code": null, "e": 6944, "s": 6847, "text": "Step 3: Extend the following class in this Java file:androidx.appcompat.widget.AppCompatTextView" }, { "code": null, "e": 6988, "s": 6944, "text": "androidx.appcompat.widget.AppCompatTextView" }, { "code": null, "e": 7056, "s": 6988, "text": "Step 4: Complete the Java code by adding the required constructors." }, { "code": null, "e": 7135, "s": 7056, "text": "Step 5: Create a method in the class wherein the typeface for the font is set." }, { "code": null, "e": 8259, "s": 7135, "text": "Step 6: Call this method in each constructor. Refer to the following code for a better understanding.CalligraffittiRegular.javaCalligraffittiRegular.javapackage com.example.android.customfonts; import android.content.Context;import android.graphics.Typeface;import android.util.AttributeSet; public class CalligraffittiRegular extends androidx.appcompat.widget.AppCompatTextView { public CalligraffittiRegular(Context context) { super(context); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs) { super(context, attrs); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initTypeface(context); } private void initTypeface(Context context) { Typeface tf = Typeface.createFromAsset( context.getAssets(), \"calligraffitti_regular.ttf\"); this.setTypeface(tf); }}" }, { "code": null, "e": 8286, "s": 8259, "text": "CalligraffittiRegular.java" }, { "code": "package com.example.android.customfonts; import android.content.Context;import android.graphics.Typeface;import android.util.AttributeSet; public class CalligraffittiRegular extends androidx.appcompat.widget.AppCompatTextView { public CalligraffittiRegular(Context context) { super(context); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs) { super(context, attrs); initTypeface(context); } public CalligraffittiRegular(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initTypeface(context); } private void initTypeface(Context context) { Typeface tf = Typeface.createFromAsset( context.getAssets(), \"calligraffitti_regular.ttf\"); this.setTypeface(tf); }}", "e": 9257, "s": 8286, "text": null }, { "code": null, "e": 10379, "s": 9257, "text": "Step 7: Now in your XML layout file, use this font class instead of of the conventional TextView tag.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <com.example.android.customfonts.CalligraffittiRegular android:id=\"@+id/textview1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.616\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.462\"/> </androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 10397, "s": 10379, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <com.example.android.customfonts.CalligraffittiRegular android:id=\"@+id/textview1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.616\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.462\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 11384, "s": 10397, "text": null }, { "code": null, "e": 11392, "s": 11384, "text": "Output:" }, { "code": null, "e": 11589, "s": 11392, "text": "With Android 8.0 (API Level 26) a simpler method was introduced for using fonts as a resource in Android Studio. The android:fontFamily attribute of the TextView class is used to specify the font." }, { "code": null, "e": 11643, "s": 11589, "text": "Step 1: Go to the XML file and go to the Design view." }, { "code": null, "e": 11702, "s": 11643, "text": "Step 2: Click the TextView you want to change the font of." }, { "code": null, "e": 11752, "s": 11702, "text": "Step 3: In the search bar, search for fontFamily." }, { "code": null, "e": 11894, "s": 11752, "text": "Step 4: In the dropdown menu, you can check out the fonts available. In case you want to explore more, scroll down and click ‘More Fonts...‘." }, { "code": null, "e": 12010, "s": 11894, "text": "Step 5: A dialog box pops up. Choose a font of your choice, choose the style you like in the preview, and click OK." }, { "code": null, "e": 12158, "s": 12010, "text": "Step 6: This would create a downloadable font and add it automatically to your project.The following files automatically get added to your project:" }, { "code": null, "e": 12219, "s": 12158, "text": "The following files automatically get added to your project:" }, { "code": null, "e": 13180, "s": 12219, "text": "Step 7: Now the XML file will be look like:activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/aref_ruqaa\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 13198, "s": 13180, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/aref_ruqaa\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 14082, "s": 13198, "text": null }, { "code": null, "e": 14090, "s": 14082, "text": "Output:" }, { "code": null, "e": 14536, "s": 14090, "text": "ConclusionWhile the last method seems easy and time-saving, however, it bundles the extra files with the APK of the app which might increase its size. Though this also ensures that the fonts are present even when the app works offline. The first method results in a smaller sized APK but the user might need access to the internet while the processing of the app if some other already present app does not have the same font stored in its cache." }, { "code": null, "e": 14551, "s": 14536, "text": "sagartomar9927" }, { "code": null, "e": 14559, "s": 14551, "text": "android" }, { "code": null, "e": 14566, "s": 14559, "text": "How To" }, { "code": null, "e": 14571, "s": 14566, "text": "Java" }, { "code": null, "e": 14576, "s": 14571, "text": "Java" }, { "code": null, "e": 14674, "s": 14576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14723, "s": 14674, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 14765, "s": 14723, "text": "How to Permanently Disable Swap in Linux?" }, { "code": null, "e": 14807, "s": 14765, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 14848, "s": 14807, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 14887, "s": 14848, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 14902, "s": 14887, "text": "Arrays in Java" }, { "code": null, "e": 14946, "s": 14902, "text": "Split() String method in Java with examples" }, { "code": null, "e": 14982, "s": 14946, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15004, "s": 14982, "text": "For-each loop in Java" } ]
Parse XML using Minidom in Python
10 Jul, 2020 DOM (document object model) is a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the help of xml.dom.minidom, which is the minimal implementation of the DOM interface. It is simpler than the full DOM API and should be considered as smaller. Steps for Parsing XML are – Import the module import xml.dom.minidom Let say, your XML files will have the following things, Use the parse function to load and parse the XML file. In the below case docs stores the result of the parse function docs = xml.dom.minidom.parse("test.xml") Let’s print the child tagname and nodename of the XML file. Python3 import xml.dom.minidom docs = xml.dom.minidom.parse("test.xml") print(docs.nodeName)print(docs.firstChild.tagName) Output: #document info Now to get the information from the tag-name, you need to call dom standard function getElementsByTagName and getAttribute for fetching the required attributes. Python3 import xml.dom.minidom docs = xml.dom.minidom.parse("test.xml") print(docs.nodeName)print(docs.firstChild.tagName) skills = docs.getElementsByTagName("skills") print("%d skills" % skills.length)for i in skills: print(i.getAttribute("name")) Output: #document info 4 skills Machine learning Deep learning Python Bootstrap Python-XML Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 366, "s": 28, "text": "DOM (document object model) is a cross-language API from W3C i.e. World Wide Web Consortium for accessing and modifying XML documents. Python enables you to parse XML files with the help of xml.dom.minidom, which is the minimal implementation of the DOM interface. It is simpler than the full DOM API and should be considered as smaller." }, { "code": null, "e": 395, "s": 366, "text": "Steps for Parsing XML are – " }, { "code": null, "e": 413, "s": 395, "text": "Import the module" }, { "code": null, "e": 437, "s": 413, "text": "import xml.dom.minidom\n" }, { "code": null, "e": 495, "s": 437, "text": "Let say, your XML files will have the following things, " }, { "code": null, "e": 613, "s": 495, "text": "Use the parse function to load and parse the XML file. In the below case docs stores the result of the parse function" }, { "code": null, "e": 655, "s": 613, "text": "docs = xml.dom.minidom.parse(\"test.xml\")\n" }, { "code": null, "e": 716, "s": 655, "text": "Let’s print the child tagname and nodename of the XML file. " }, { "code": null, "e": 724, "s": 716, "text": "Python3" }, { "code": "import xml.dom.minidom docs = xml.dom.minidom.parse(\"test.xml\") print(docs.nodeName)print(docs.firstChild.tagName)", "e": 841, "s": 724, "text": null }, { "code": null, "e": 849, "s": 841, "text": "Output:" }, { "code": null, "e": 864, "s": 849, "text": "#document\ninfo" }, { "code": null, "e": 1026, "s": 864, "text": "Now to get the information from the tag-name, you need to call dom standard function getElementsByTagName and getAttribute for fetching the required attributes. " }, { "code": null, "e": 1034, "s": 1026, "text": "Python3" }, { "code": "import xml.dom.minidom docs = xml.dom.minidom.parse(\"test.xml\") print(docs.nodeName)print(docs.firstChild.tagName) skills = docs.getElementsByTagName(\"skills\") print(\"%d skills\" % skills.length)for i in skills: print(i.getAttribute(\"name\"))", "e": 1284, "s": 1034, "text": null }, { "code": null, "e": 1292, "s": 1284, "text": "Output:" }, { "code": null, "e": 1365, "s": 1292, "text": "#document\ninfo\n4 skills\nMachine learning\nDeep learning\nPython\nBootstrap\n" }, { "code": null, "e": 1376, "s": 1365, "text": "Python-XML" }, { "code": null, "e": 1383, "s": 1376, "text": "Python" } ]
Java Program to Convert Date to TimeStamp
22 Oct, 2021 We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package). Example: Input: Date is 19 October 2021 Output: 2021-10-19 18:11:24 Explanation: Date would be printed along with the current time to milliseconds. The TimeStamp class presents formatting and parsing methods to support JDBC escape syntax. It also combines the ability to hold the SQL TIMESTAMP fractional seconds value. How to use TimeStamp Class? Import the java.sql.Timestamp package. Import the java.util.Date package Create an object of the Date class. Convert it to long using getTime() method Syntax: public long getTime() Parameters: The function does not accept any parameter. Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM. Create an object of the Timestamp class and pass the value returned by the getTime() method. Finally, print this Timestamp object value. Example: Java // Java Program to convert date to time stamp import java.sql.Timestamp;import java.util.Date;public class GFG_Article { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the object of the Timestamp class Timestamp ts = new Timestamp(date.getTime()); // printing the timestamp of the current date System.out.println(ts); }} 2021-10-19 20:18:08.813 We can format the Timestamp value using SimpleDateFormat class. Initially, by using the Timestamp class, the time is getting displayed in a standard format, but we can format it to our own choice using SimpleDateFormat class. Example: Java // Java program to convert date to time-stamp using// SimpleDataFormat class and TimeStamp class import java.sql.Timestamp;import java.util.Date;import java.text.SimpleDateFormat; public class GFG { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the timestamp object Timestamp ts = new Timestamp(date.getTime()); // using SimpleDateFormat class,we can format the // time-stamp according to ourselves // getting the timestamp upto sec SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(formatter.format(ts)); // getting the timestamp to seconds SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // printing the timestamp System.out.println(formatter1.format(ts)); }} 2021-10-19 20:21:34 2021-10-19 20:21 nishkarshgandhi Java-Date-Time Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Collections in Java Set in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2021" }, { "code": null, "e": 125, "s": 28, "text": "We can convert date to timestamp using the Timestamp class which is present in the SQL package. " }, { "code": null, "e": 188, "s": 125, "text": "The constructor of the time-stamp class requires a long value." }, { "code": null, "e": 323, "s": 188, "text": "So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package)." }, { "code": null, "e": 332, "s": 323, "text": "Example:" }, { "code": null, "e": 472, "s": 332, "text": "Input: Date is 19 October 2021 \nOutput: 2021-10-19 18:11:24\nExplanation: Date would be printed along with the current time to milliseconds." }, { "code": null, "e": 644, "s": 472, "text": "The TimeStamp class presents formatting and parsing methods to support JDBC escape syntax. It also combines the ability to hold the SQL TIMESTAMP fractional seconds value." }, { "code": null, "e": 672, "s": 644, "text": "How to use TimeStamp Class?" }, { "code": null, "e": 711, "s": 672, "text": "Import the java.sql.Timestamp package." }, { "code": null, "e": 745, "s": 711, "text": "Import the java.util.Date package" }, { "code": null, "e": 781, "s": 745, "text": "Create an object of the Date class." }, { "code": null, "e": 823, "s": 781, "text": "Convert it to long using getTime() method" }, { "code": null, "e": 831, "s": 823, "text": "Syntax:" }, { "code": null, "e": 853, "s": 831, "text": "public long getTime()" }, { "code": null, "e": 909, "s": 853, "text": "Parameters: The function does not accept any parameter." }, { "code": null, "e": 998, "s": 909, "text": "Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM." }, { "code": null, "e": 1091, "s": 998, "text": "Create an object of the Timestamp class and pass the value returned by the getTime() method." }, { "code": null, "e": 1135, "s": 1091, "text": "Finally, print this Timestamp object value." }, { "code": null, "e": 1144, "s": 1135, "text": "Example:" }, { "code": null, "e": 1149, "s": 1144, "text": "Java" }, { "code": "// Java Program to convert date to time stamp import java.sql.Timestamp;import java.util.Date;public class GFG_Article { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the object of the Timestamp class Timestamp ts = new Timestamp(date.getTime()); // printing the timestamp of the current date System.out.println(ts); }}", "e": 1602, "s": 1149, "text": null }, { "code": null, "e": 1626, "s": 1602, "text": "2021-10-19 20:18:08.813" }, { "code": null, "e": 1690, "s": 1626, "text": "We can format the Timestamp value using SimpleDateFormat class." }, { "code": null, "e": 1852, "s": 1690, "text": "Initially, by using the Timestamp class, the time is getting displayed in a standard format, but we can format it to our own choice using SimpleDateFormat class." }, { "code": null, "e": 1861, "s": 1852, "text": "Example:" }, { "code": null, "e": 1866, "s": 1861, "text": "Java" }, { "code": "// Java program to convert date to time-stamp using// SimpleDataFormat class and TimeStamp class import java.sql.Timestamp;import java.util.Date;import java.text.SimpleDateFormat; public class GFG { public static void main(String args[]) { // getting the system date Date date = new Date(); // getting the timestamp object Timestamp ts = new Timestamp(date.getTime()); // using SimpleDateFormat class,we can format the // time-stamp according to ourselves // getting the timestamp upto sec SimpleDateFormat formatter = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\"); System.out.println(formatter.format(ts)); // getting the timestamp to seconds SimpleDateFormat formatter1 = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\"); // printing the timestamp System.out.println(formatter1.format(ts)); }}", "e": 2831, "s": 1866, "text": null }, { "code": null, "e": 2868, "s": 2831, "text": "2021-10-19 20:21:34\n2021-10-19 20:21" }, { "code": null, "e": 2884, "s": 2868, "text": "nishkarshgandhi" }, { "code": null, "e": 2899, "s": 2884, "text": "Java-Date-Time" }, { "code": null, "e": 2906, "s": 2899, "text": "Picked" }, { "code": null, "e": 2930, "s": 2906, "text": "Technical Scripter 2020" }, { "code": null, "e": 2935, "s": 2930, "text": "Java" }, { "code": null, "e": 2949, "s": 2935, "text": "Java Programs" }, { "code": null, "e": 2968, "s": 2949, "text": "Technical Scripter" }, { "code": null, "e": 2973, "s": 2968, "text": "Java" }, { "code": null, "e": 3071, "s": 2973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3090, "s": 3071, "text": "Interfaces in Java" }, { "code": null, "e": 3108, "s": 3090, "text": "ArrayList in Java" }, { "code": null, "e": 3140, "s": 3108, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3160, "s": 3140, "text": "Collections in Java" }, { "code": null, "e": 3172, "s": 3160, "text": "Set in Java" }, { "code": null, "e": 3200, "s": 3172, "text": "Initializing a List in Java" }, { "code": null, "e": 3226, "s": 3200, "text": "Java Programming Examples" }, { "code": null, "e": 3270, "s": 3226, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 3317, "s": 3270, "text": "Implementing a Linked List in Java using Class" } ]
Stack machine in Computer Organisation
19 Feb, 2020 Instruction formats are classified into different types depending upon the CPU organization. CPU organization is again classified into three types based on internal storage: Stack machine, Accumulator machine, General purpose organization or General register. In this article, we will learn about the stack machine in computer organizations. Stack Machine:In the stack machine, data is available at the top of the stack by default. The stack acts as a source and destination, push and pop instructions are used to access instructions and data from the stack. There is no need to pass the source and destination address because the default address is top of the stack. In the stack machine, there is no need to pass explicit addresses in the instruction. Therefore the instruction format consists only of the OPCODE (Operation Code) field. This instruction format is known as Zero address instruction. The two operations of the stack are insertion (push) and deletion (pop) of items in the Stack. However, nothing is pushed or popped in a computer stack. Example:Perform the following set of instructions intended for execution on a stack machine: PUSH B, PUSH X, ADD, POP C, PUSH C, PUSH Y, SUB, POP Z First PUSH B and X in a stack, then to add first POP X then B, ADD (B+X), POP C=B+X (no data with name C, so the data present is stored in variable C) then POP C.Similarly, to perform SUB (Y-C) first perform POP operation POP as Z. See in figure below for better understanding: Technical Scripter 2019 Computer Organization & Architecture GATE CS Stack Technical Scripter Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 370, "s": 28, "text": "Instruction formats are classified into different types depending upon the CPU organization. CPU organization is again classified into three types based on internal storage: Stack machine, Accumulator machine, General purpose organization or General register. In this article, we will learn about the stack machine in computer organizations." }, { "code": null, "e": 929, "s": 370, "text": "Stack Machine:In the stack machine, data is available at the top of the stack by default. The stack acts as a source and destination, push and pop instructions are used to access instructions and data from the stack. There is no need to pass the source and destination address because the default address is top of the stack. In the stack machine, there is no need to pass explicit addresses in the instruction. Therefore the instruction format consists only of the OPCODE (Operation Code) field. This instruction format is known as Zero address instruction." }, { "code": null, "e": 1082, "s": 929, "text": "The two operations of the stack are insertion (push) and deletion (pop) of items in the Stack. However, nothing is pushed or popped in a computer stack." }, { "code": null, "e": 1175, "s": 1082, "text": "Example:Perform the following set of instructions intended for execution on a stack machine:" }, { "code": null, "e": 1238, "s": 1175, "text": "PUSH B, \nPUSH X, \nADD, \nPOP C, \nPUSH C, \nPUSH Y, \nSUB, \nPOP Z " }, { "code": null, "e": 1516, "s": 1238, "text": "First PUSH B and X in a stack, then to add first POP X then B, ADD (B+X), POP C=B+X (no data with name C, so the data present is stored in variable C) then POP C.Similarly, to perform SUB (Y-C) first perform POP operation POP as Z. See in figure below for better understanding:" }, { "code": null, "e": 1540, "s": 1516, "text": "Technical Scripter 2019" }, { "code": null, "e": 1577, "s": 1540, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1585, "s": 1577, "text": "GATE CS" }, { "code": null, "e": 1591, "s": 1585, "text": "Stack" }, { "code": null, "e": 1610, "s": 1591, "text": "Technical Scripter" }, { "code": null, "e": 1616, "s": 1610, "text": "Stack" } ]
How to Implement Notification Counter in Android?
20 Sep, 2021 Notification Counter basically counts the notifications that you got through an application and shows on the top of your application icon so that you get to know you get new messages or any new update without opening your application or specific feature like the message button in Instagram. Notification counter is a feature that is provided in almost all android applications nowadays for example Facebook, Whatsapp, Instagram, YouTube, Gmail these are some social apps that we use in our day-to-day life so that exactly the Notification counter feature does? It’s used for various purposes like: To tell user that you got a new messageTo tell how many unread messages they have To notify users that a new feature or content is uploaded for example whenever your subscribed channel uploads a video on Youtube your Youtube notification count number increases. To tell user that you got a new message To tell how many unread messages they have To notify users that a new feature or content is uploaded for example whenever your subscribed channel uploads a video on Youtube your Youtube notification count number increases. In this article, we are going to build a simple application that counts the number of notifications with the help of two buttons increment and decrement. Whenever the user clicks on the increment button the notification count increases and whenever the user clicks on the decrement button the notification count decreases along with these two buttons we are also going to implement or use a 3rd button that is a reset button that directly sets the notification count to the zero. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create a new Vector asset for notification bell by following these steps. Right-click on drawable > new > vector asset > search for notification icon and select > finish. We are going to use this icon to show our notification count on top of it. Now, what exactly is the vector asset that we use in this step. Vector Asset: Vector Asset is an Android Studio tool that allows you to add material icons and import Scalable Vector Graphic (SVG) and Adobe Photoshop Document (PSD) files as vector drawable resources to your project. Note: You can use customize notification bell icon as well by selecting it from your device storage but here we are using by default notification icon that is provided by the android studio. Image for reference: FIG = VECTOR ASSET XML <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" <!--width of the bell icon --> android:height="24dp" <!-- height of the bell icon --> android:viewportWidth="24" <!-- Used to define the width of the viewport space. --> android:viewportHeight="24" <!-- Used to define the height of the viewport space. --> android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z"/></vector> Step 3: Working with the activity_main.xml file In this step, we are going to design our three buttons named Increment , decrement and reset along with our notification bell in the activity_main.xml file with the help of vector asset that we create in step 2 and to show notification count we are going to use a textview and set that textview on the top of our bell icon that we are implementing using image view also we use an ImageView to show the image of gfg logo. Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/decrement" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="168dp" android:layout_marginTop="30dp" android:layout_marginEnd="155dp" android:text="DECREMENT( - )" android:textColor="#0F9D58" app:layout_constraintBottom_toTopOf="@+id/reset" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.45" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/increment" app:layout_constraintVertical_bias="0.0" /> <Button android:id="@+id/increment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="168dp" android:layout_marginTop="64dp" android:layout_marginEnd="155dp" android:text="INCREMENT( + )" android:textColor="#0F9D58" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.45" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <Button android:id="@+id/reset" android:layout_width="125dp" android:layout_height="55dp" android:layout_marginStart="168dp" android:layout_marginTop="25dp" android:layout_marginEnd="155dp" android:layout_marginBottom="168dp" android:text="RESET" android:textColor="#0F9D58" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.486" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/decrement" /> <ImageView android:id="@+id/imageView" android:layout_width="91dp" android:layout_height="57dp" android:layout_marginTop="188dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.531" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/notificationbell" /> <TextView android:id="@+id/textView" android:layout_width="30dp" android:layout_height="30dp" android:layout_marginBottom="24dp" android:background="@drawable/custombutton1" android:paddingTop="5sp" android:text="0" android:textAlignment="center" android:textColor="@color/white" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/imageView" app:layout_constraintEnd_toEndOf="@+id/imageView" app:layout_constraintHorizontal_bias="0.803" app:layout_constraintStart_toStartOf="@+id/imageView" /> <ImageView android:id="@+id/imageView2" android:layout_width="136dp" android:layout_height="125dp" app:layout_constraintBottom_toTopOf="@+id/imageView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/gfg" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: In this step, we are going to implement our methods to perform operations like increment, decrement, reset. To do this create a new java class by doing following the steps. Right-click on project name > New > class > finish. Below is the code for the Notificationcount.java file. Java import android.util.Log;import android.view.View;import android.widget.TextView; public class notificationcount { private TextView notificationNumber; // maximum count limit private final int MAX_NUMBER = 99; // minimum count limit private final int MIN_NUMBER = 0; // initial count private int notification_number_counter = 0; public notificationcount(View view) { // finding textview through id textview // in notification number variable notificationNumber = view.findViewById(R.id.textView); } // increment method public void increment() { // checking condition if notification_counter-number // is greater than max number or not if (notification_number_counter > MAX_NUMBER) { // printing message maximum number reached Log.d("Counter", "Maximum number reached"); } else { // if condition fails then increment the count by 1 notification_number_counter++; // returning increased value notificationNumber.setText(String.valueOf(notification_number_counter)); } } // decrement method public void decrement() { // checking condition if notification_number_count // is less than min number or not if (notification_number_counter <= MIN_NUMBER) { // if true then message minimum number reached Log.d("Counter", "Minimum number reached"); } else { // decrease if condition fails notification_number_counter--; // returning decrease count notificationNumber.setText(String.valueOf(notification_number_counter)); } } // rest method public void reset() { // checking if notification_number_count // is already zero or not if (notification_number_counter == 0) { // if true message already zero Log.d("alert", " notification count is already 0 "); } else { // else setting count to zero notification_number_counter = 0; // returning updated value notificationNumber.setText(String.valueOf(notification_number_counter)); } } } Step 5: Working with the MainActivity.java file In this final step we are going to implement onclick listeners to our three buttons named increment, decrement, reset in our MainActivity.java file and call functions increment, decrement, reset that we created in the previous step. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // initializing 3 button variables b1,b2,b3 Button b1, b2, b3; // initializing textview variable number TextView number; // object of Notificationcount class notificationcount notificationcount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // finding increment button through id in b1 b1 = findViewById(R.id.increment); // finding decrement button through id in b2 b2 = findViewById(R.id.decrement); // finding reset button through id in b3 b3 = findViewById(R.id.reset); // creating new object of notificationcount class notificationcount = new notificationcount(findViewById(R.id.textView)); // increment button b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling increment method notificationcount.increment(); } }); // decrement button b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling decrement button notificationcount.decrement(); } }); // reset button b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling reset button notificationcount.reset(); } }); }} Output: FIG = NOTIFICATION COUNTER Output Video: Project Link: Click Here anikaseth98 Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Sep, 2021" }, { "code": null, "e": 591, "s": 28, "text": "Notification Counter basically counts the notifications that you got through an application and shows on the top of your application icon so that you get to know you get new messages or any new update without opening your application or specific feature like the message button in Instagram. Notification counter is a feature that is provided in almost all android applications nowadays for example Facebook, Whatsapp, Instagram, YouTube, Gmail these are some social apps that we use in our day-to-day life so that exactly the Notification counter feature does? " }, { "code": null, "e": 629, "s": 591, "text": "It’s used for various purposes like: " }, { "code": null, "e": 891, "s": 629, "text": "To tell user that you got a new messageTo tell how many unread messages they have To notify users that a new feature or content is uploaded for example whenever your subscribed channel uploads a video on Youtube your Youtube notification count number increases." }, { "code": null, "e": 931, "s": 891, "text": "To tell user that you got a new message" }, { "code": null, "e": 975, "s": 931, "text": "To tell how many unread messages they have " }, { "code": null, "e": 1155, "s": 975, "text": "To notify users that a new feature or content is uploaded for example whenever your subscribed channel uploads a video on Youtube your Youtube notification count number increases." }, { "code": null, "e": 1800, "s": 1155, "text": "In this article, we are going to build a simple application that counts the number of notifications with the help of two buttons increment and decrement. Whenever the user clicks on the increment button the notification count increases and whenever the user clicks on the decrement button the notification count decreases along with these two buttons we are also going to implement or use a 3rd button that is a reset button that directly sets the notification count to the zero. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1829, "s": 1800, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1991, "s": 1829, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 2310, "s": 1991, "text": "Step 2: Create a new Vector asset for notification bell by following these steps. Right-click on drawable > new > vector asset > search for notification icon and select > finish. We are going to use this icon to show our notification count on top of it. Now, what exactly is the vector asset that we use in this step. " }, { "code": null, "e": 2530, "s": 2310, "text": "Vector Asset: Vector Asset is an Android Studio tool that allows you to add material icons and import Scalable Vector Graphic (SVG) and Adobe Photoshop Document (PSD) files as vector drawable resources to your project. " }, { "code": null, "e": 2721, "s": 2530, "text": "Note: You can use customize notification bell icon as well by selecting it from your device storage but here we are using by default notification icon that is provided by the android studio." }, { "code": null, "e": 2743, "s": 2721, "text": "Image for reference: " }, { "code": null, "e": 2762, "s": 2743, "text": "FIG = VECTOR ASSET" }, { "code": null, "e": 2766, "s": 2762, "text": "XML" }, { "code": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" <!--width of the bell icon --> android:height=\"24dp\" <!-- height of the bell icon --> android:viewportWidth=\"24\" <!-- Used to define the width of the viewport space. --> android:viewportHeight=\"24\" <!-- Used to define the height of the viewport space. --> android:tint=\"?attr/colorControlNormal\"> <path android:fillColor=\"@android:color/white\" android:pathData=\"M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z\"/></vector>", "e": 3445, "s": 2766, "text": null }, { "code": null, "e": 3493, "s": 3445, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 3914, "s": 3493, "text": "In this step, we are going to design our three buttons named Increment , decrement and reset along with our notification bell in the activity_main.xml file with the help of vector asset that we create in step 2 and to show notification count we are going to use a textview and set that textview on the top of our bell icon that we are implementing using image view also we use an ImageView to show the image of gfg logo." }, { "code": null, "e": 4057, "s": 3914, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 4061, "s": 4057, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/decrement\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"168dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"155dp\" android:text=\"DECREMENT( - )\" android:textColor=\"#0F9D58\" app:layout_constraintBottom_toTopOf=\"@+id/reset\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.45\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/increment\" app:layout_constraintVertical_bias=\"0.0\" /> <Button android:id=\"@+id/increment\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"168dp\" android:layout_marginTop=\"64dp\" android:layout_marginEnd=\"155dp\" android:text=\"INCREMENT( + )\" android:textColor=\"#0F9D58\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.45\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" /> <Button android:id=\"@+id/reset\" android:layout_width=\"125dp\" android:layout_height=\"55dp\" android:layout_marginStart=\"168dp\" android:layout_marginTop=\"25dp\" android:layout_marginEnd=\"155dp\" android:layout_marginBottom=\"168dp\" android:text=\"RESET\" android:textColor=\"#0F9D58\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.486\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/decrement\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"91dp\" android:layout_height=\"57dp\" android:layout_marginTop=\"188dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.531\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:srcCompat=\"@drawable/notificationbell\" /> <TextView android:id=\"@+id/textView\" android:layout_width=\"30dp\" android:layout_height=\"30dp\" android:layout_marginBottom=\"24dp\" android:background=\"@drawable/custombutton1\" android:paddingTop=\"5sp\" android:text=\"0\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"@+id/imageView\" app:layout_constraintEnd_toEndOf=\"@+id/imageView\" app:layout_constraintHorizontal_bias=\"0.803\" app:layout_constraintStart_toStartOf=\"@+id/imageView\" /> <ImageView android:id=\"@+id/imageView2\" android:layout_width=\"136dp\" android:layout_height=\"125dp\" app:layout_constraintBottom_toTopOf=\"@+id/imageView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:srcCompat=\"@drawable/gfg\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 7698, "s": 4061, "text": null }, { "code": null, "e": 7711, "s": 7702, "text": "Step 4: " }, { "code": null, "e": 7996, "s": 7713, "text": "In this step, we are going to implement our methods to perform operations like increment, decrement, reset. To do this create a new java class by doing following the steps. Right-click on project name > New > class > finish. Below is the code for the Notificationcount.java file. " }, { "code": null, "e": 8003, "s": 7998, "text": "Java" }, { "code": "import android.util.Log;import android.view.View;import android.widget.TextView; public class notificationcount { private TextView notificationNumber; // maximum count limit private final int MAX_NUMBER = 99; // minimum count limit private final int MIN_NUMBER = 0; // initial count private int notification_number_counter = 0; public notificationcount(View view) { // finding textview through id textview // in notification number variable notificationNumber = view.findViewById(R.id.textView); } // increment method public void increment() { // checking condition if notification_counter-number // is greater than max number or not if (notification_number_counter > MAX_NUMBER) { // printing message maximum number reached Log.d(\"Counter\", \"Maximum number reached\"); } else { // if condition fails then increment the count by 1 notification_number_counter++; // returning increased value notificationNumber.setText(String.valueOf(notification_number_counter)); } } // decrement method public void decrement() { // checking condition if notification_number_count // is less than min number or not if (notification_number_counter <= MIN_NUMBER) { // if true then message minimum number reached Log.d(\"Counter\", \"Minimum number reached\"); } else { // decrease if condition fails notification_number_counter--; // returning decrease count notificationNumber.setText(String.valueOf(notification_number_counter)); } } // rest method public void reset() { // checking if notification_number_count // is already zero or not if (notification_number_counter == 0) { // if true message already zero Log.d(\"alert\", \" notification count is already 0 \"); } else { // else setting count to zero notification_number_counter = 0; // returning updated value notificationNumber.setText(String.valueOf(notification_number_counter)); } } }", "e": 10217, "s": 8003, "text": null }, { "code": null, "e": 10270, "s": 10221, "text": "Step 5: Working with the MainActivity.java file " }, { "code": null, "e": 10629, "s": 10272, "text": "In this final step we are going to implement onclick listeners to our three buttons named increment, decrement, reset in our MainActivity.java file and call functions increment, decrement, reset that we created in the previous step. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 10636, "s": 10631, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // initializing 3 button variables b1,b2,b3 Button b1, b2, b3; // initializing textview variable number TextView number; // object of Notificationcount class notificationcount notificationcount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // finding increment button through id in b1 b1 = findViewById(R.id.increment); // finding decrement button through id in b2 b2 = findViewById(R.id.decrement); // finding reset button through id in b3 b3 = findViewById(R.id.reset); // creating new object of notificationcount class notificationcount = new notificationcount(findViewById(R.id.textView)); // increment button b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling increment method notificationcount.increment(); } }); // decrement button b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling decrement button notificationcount.decrement(); } }); // reset button b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling reset button notificationcount.reset(); } }); }}", "e": 12416, "s": 10636, "text": null }, { "code": null, "e": 12429, "s": 12420, "text": "Output: " }, { "code": null, "e": 12458, "s": 12431, "text": "FIG = NOTIFICATION COUNTER" }, { "code": null, "e": 12474, "s": 12460, "text": "Output Video:" }, { "code": null, "e": 12503, "s": 12478, "text": "Project Link: Click Here" }, { "code": null, "e": 12517, "s": 12505, "text": "anikaseth98" }, { "code": null, "e": 12525, "s": 12517, "text": "Android" }, { "code": null, "e": 12530, "s": 12525, "text": "Java" }, { "code": null, "e": 12535, "s": 12530, "text": "Java" }, { "code": null, "e": 12543, "s": 12535, "text": "Android" } ]
PostgreSQL – LIKE operator
28 Aug, 2020 The PostgreSQL LIKE operator is used query data using pattern matching techniques. Its result include strings that are case-sensitive and follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below: Percent ( %) for matching any sequence of characters. Underscore ( _) for matching any single character. Syntax: string LIKE pattern; For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples. Now, let’s look into a few examples. Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that begins with “K” using the LIKE operator in our sample database. SELECT first_name, last_name FROM customer WHERE first_name LIKE 'K%'; Output: Notice few things in the above example, the WHERE clause contains a special expression: the first_name, the LIKE operator, and a string that contains a percent (%) character, which is referred to as a pattern. Example 2:Here we will query for customers whose first name begins with any single character, is followed by the literal string “her”, and ends with any number of characters using the LIKE operator in our sample database. SELECT first_name, last_name FROM customer WHERE first_name LIKE '_her%'; Output: postgreSQL-operators PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 326, "s": 28, "text": "The PostgreSQL LIKE operator is used query data using pattern matching techniques. Its result include strings that are case-sensitive and follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below:" }, { "code": null, "e": 380, "s": 326, "text": "Percent ( %) for matching any sequence of characters." }, { "code": null, "e": 431, "s": 380, "text": "Underscore ( _) for matching any single character." }, { "code": null, "e": 460, "s": 431, "text": "Syntax: string LIKE pattern;" }, { "code": null, "e": 626, "s": 460, "text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples." }, { "code": null, "e": 663, "s": 626, "text": "Now, let’s look into a few examples." }, { "code": null, "e": 880, "s": 663, "text": "Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that begins with “K” using the LIKE operator in our sample database." }, { "code": null, "e": 971, "s": 880, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n first_name LIKE 'K%';" }, { "code": null, "e": 979, "s": 971, "text": "Output:" }, { "code": null, "e": 1189, "s": 979, "text": "Notice few things in the above example, the WHERE clause contains a special expression: the first_name, the LIKE operator, and a string that contains a percent (%) character, which is referred to as a pattern." }, { "code": null, "e": 1411, "s": 1189, "text": "Example 2:Here we will query for customers whose first name begins with any single character, is followed by the literal string “her”, and ends with any number of characters using the LIKE operator in our sample database." }, { "code": null, "e": 1501, "s": 1411, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n first_name LIKE '_her%';" }, { "code": null, "e": 1509, "s": 1501, "text": "Output:" }, { "code": null, "e": 1530, "s": 1509, "text": "postgreSQL-operators" }, { "code": null, "e": 1541, "s": 1530, "text": "PostgreSQL" } ]
Program to print the Fish Pattern
23 Nov, 2021 Given an integer N, the task is to print a pattern of fish over 2N+1 rows. Example: Input: N=3Output: * *** * ***** ************ ***** ** *** * * Input: N=5Output: * *** * ***** ** ******* *** ********* ******************** ********* **** ******* *** ***** ** *** * * Approach: The fish consists of three parts: Upper Part: Over N rows. Middle Part: Singe row in the middle Lower Part: Over N rows Now, let’s try to understand the pattern using an example:For N=3, the fish is: Now, to solve this question, follow the steps below: First, create the upper part:Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star.For the middle part, just print both stars1 and stars2, as no spaces appear in this row.Now, to get the lower part, reverse the algorithm for the upper part.After the loop ends, the pattern of fish will be created. First, create the upper part:Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star. Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star. As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially. Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star. For the middle part, just print both stars1 and stars2, as no spaces appear in this row. Now, to get the lower part, reverse the algorithm for the upper part. After the loop ends, the pattern of fish will be created. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the pattern of a fish// over N rowsvoid printFish(int N){ string spaces1 = "", spaces2 = ""; string stars1 = "*", stars2 = ""; for (int i = 0; i < N; ++i) { spaces1 += ' '; } spaces2 = spaces1; for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; spaces1.pop_back(); stars1 += "**"; stars2 += "*"; } // For middle part if (i == N) { cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; } // For lower part if (i > N) { spaces1 += ' '; stars1.pop_back(); stars1.pop_back(); stars2.pop_back(); cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; } }} // Driver Codeint main(){ int N = 5; printFish(N);} // Java program for the above approachclass GFG { // Function to print the pattern of a fish // over N rows public static void printFish(int N) { String spaces1 = ""; String stars1 = "*", stars2 = ""; for (int i = 0; i < N; ++i) { spaces1 += ' '; } for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); spaces1 = spaces1.substring(0, spaces1.length() - 1); stars1 += "**"; stars2 += "*"; } // For middle part if (i == N) { System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); } // For lower part if (i > N) { spaces1 += ' '; stars1 = stars1.substring(0, stars1.length() - 1); stars1 = stars1.substring(0, stars1.length() - 1); stars2 = stars2.substring(0, stars2.length() - 1); System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); } } } // Driver Code public static void main(String args[]) { int N = 5; printFish(N); }} // This code is contributed by gfgking. # Python3 program for the above approach # Function to print the pattern of a fish# over N rowsdef printFish(N) : spaces1 = ""; spaces2 = ""; stars1 = "*"; stars2 = ""; for i in range(N) : spaces1 += ' '; spaces2 = spaces1; for i in range( 2 * N + 1) : # For upper part if (i < N) : print(spaces1,end=""); print(stars1,end=""); print(spaces1,end=""); print(spaces1,end=""); print(stars2); spaces1 = spaces1[:-1] stars1 += "**"; stars2 += "*"; # For middle part if (i == N) : print(spaces1,end=""); print(stars1,end=""); print(spaces1,end=""); print(spaces1,end=""); print(stars2); # For lower part if (i > N) : spaces1 += ' '; stars1 = stars1[:-1]; stars1 = stars1[:-1]; stars2 = stars2[:-1]; print(spaces1,end=""); print(stars1,end="") print(spaces1,end=""); print(spaces1,end=""); print(stars2); # Driver Codeif __name__ == "__main__" : N = 5; printFish(N); # This code is contributed by AnkThon // C# program for the above approachusing System;class GFG { // Function to print the pattern of a fish // over N rows static void printFish(int N) { string spaces1 = ""; string stars1 = "*", stars2 = ""; for (int i = 0; i < N; ++i) { spaces1 += ' '; } for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + "\n"); spaces1 = spaces1.Substring(0, spaces1.Length - 1); stars1 += "**"; stars2 += "*"; } // For middle part if (i == N) { Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + "\n"); } // For lower part if (i > N) { spaces1 += ' '; stars1 = stars1.Substring(0, stars1.Length - 1); stars1 = stars1.Substring(0, stars1.Length - 1); stars2 = stars2.Substring(0, stars2.Length - 1); Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + "\n"); } } } // Driver Code public static void Main() { int N = 5; printFish(N); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript program for the above approach // Function to print the pattern of a fish // over N rows const printFish = (N) => { let spaces1 = "", spaces2 = ""; let stars1 = "*", stars2 = ""; for (let i = 0; i < N; ++i) { spaces1 += " "; } spaces2 = spaces1; for (let i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); spaces1 = spaces1.substr(0, spaces1.length - 10); stars1 += "**"; stars2 += "*"; } // For middle part if (i == N) { document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); } // For lower part if (i > N) { spaces1 += " "; stars1 = stars1.substr(0, stars1.length - 2); stars2 = stars2.substr(0, stars2.length - 1); document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); } } } // Driver Code let N = 5; printFish(N); // This code is contributed by rakeshsahni </script> * *** * ***** ** ******* *** ********* **** **************** ********* **** ******* *** ***** ** *** * * Time Complexity: O(N)Auxiliary Space: O(N) ankthon gfgking rakeshsahni samim2000 Pattern Searching Program Output Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Nov, 2021" }, { "code": null, "e": 128, "s": 53, "text": "Given an integer N, the task is to print a pattern of fish over 2N+1 rows." }, { "code": null, "e": 137, "s": 128, "text": "Example:" }, { "code": null, "e": 247, "s": 137, "text": "Input: N=3Output: * *** * ***** ************ ***** ** *** * * " }, { "code": null, "e": 494, "s": 247, "text": "Input: N=5Output: * *** * ***** ** ******* *** ********* ******************** ********* **** ******* *** ***** ** *** * * " }, { "code": null, "e": 538, "s": 494, "text": "Approach: The fish consists of three parts:" }, { "code": null, "e": 563, "s": 538, "text": "Upper Part: Over N rows." }, { "code": null, "e": 600, "s": 563, "text": "Middle Part: Singe row in the middle" }, { "code": null, "e": 624, "s": 600, "text": "Lower Part: Over N rows" }, { "code": null, "e": 704, "s": 624, "text": "Now, let’s try to understand the pattern using an example:For N=3, the fish is:" }, { "code": null, "e": 757, "s": 704, "text": "Now, to solve this question, follow the steps below:" }, { "code": null, "e": 1463, "s": 757, "text": "First, create the upper part:Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star.For the middle part, just print both stars1 and stars2, as no spaces appear in this row.Now, to get the lower part, reverse the algorithm for the upper part.After the loop ends, the pattern of fish will be created." }, { "code": null, "e": 1955, "s": 1463, "text": "First, create the upper part:Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star." }, { "code": null, "e": 2418, "s": 1955, "text": "Run a loop for i=0 to i<N, and in each iteration of the loop:As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially.Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star." }, { "code": null, "e": 2712, "s": 2418, "text": "As depicted in the above image that first a string, say spaces1 having M (initially M=N) spaces appear, then a layer of stars, let’s say stars1 having only 1 star, then the string spaces1 appears 2 times (having 2*M spaces) and then another layer of stars, say stars2 having 0 stars initially." }, { "code": null, "e": 2821, "s": 2712, "text": "Now in each iteration, spaces1 got reduced by a space, stars1 got increased by 2 stars and stars2 by 1 star." }, { "code": null, "e": 2910, "s": 2821, "text": "For the middle part, just print both stars1 and stars2, as no spaces appear in this row." }, { "code": null, "e": 2980, "s": 2910, "text": "Now, to get the lower part, reverse the algorithm for the upper part." }, { "code": null, "e": 3038, "s": 2980, "text": "After the loop ends, the pattern of fish will be created." }, { "code": null, "e": 3089, "s": 3038, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 3093, "s": 3089, "text": "C++" }, { "code": null, "e": 3098, "s": 3093, "text": "Java" }, { "code": null, "e": 3106, "s": 3098, "text": "Python3" }, { "code": null, "e": 3109, "s": 3106, "text": "C#" }, { "code": null, "e": 3120, "s": 3109, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the pattern of a fish// over N rowsvoid printFish(int N){ string spaces1 = \"\", spaces2 = \"\"; string stars1 = \"*\", stars2 = \"\"; for (int i = 0; i < N; ++i) { spaces1 += ' '; } spaces2 = spaces1; for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; spaces1.pop_back(); stars1 += \"**\"; stars2 += \"*\"; } // For middle part if (i == N) { cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; } // For lower part if (i > N) { spaces1 += ' '; stars1.pop_back(); stars1.pop_back(); stars2.pop_back(); cout << spaces1 << stars1 << spaces1 << spaces1 << stars2 << endl; } }} // Driver Codeint main(){ int N = 5; printFish(N);}", "e": 4244, "s": 3120, "text": null }, { "code": "// Java program for the above approachclass GFG { // Function to print the pattern of a fish // over N rows public static void printFish(int N) { String spaces1 = \"\"; String stars1 = \"*\", stars2 = \"\"; for (int i = 0; i < N; ++i) { spaces1 += ' '; } for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); spaces1 = spaces1.substring(0, spaces1.length() - 1); stars1 += \"**\"; stars2 += \"*\"; } // For middle part if (i == N) { System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); } // For lower part if (i > N) { spaces1 += ' '; stars1 = stars1.substring(0, stars1.length() - 1); stars1 = stars1.substring(0, stars1.length() - 1); stars2 = stars2.substring(0, stars2.length() - 1); System.out.print(spaces1 + stars1 + spaces1 + spaces1); System.out.println(stars2); } } } // Driver Code public static void main(String args[]) { int N = 5; printFish(N); }} // This code is contributed by gfgking.", "e": 5672, "s": 4244, "text": null }, { "code": "# Python3 program for the above approach # Function to print the pattern of a fish# over N rowsdef printFish(N) : spaces1 = \"\"; spaces2 = \"\"; stars1 = \"*\"; stars2 = \"\"; for i in range(N) : spaces1 += ' '; spaces2 = spaces1; for i in range( 2 * N + 1) : # For upper part if (i < N) : print(spaces1,end=\"\"); print(stars1,end=\"\"); print(spaces1,end=\"\"); print(spaces1,end=\"\"); print(stars2); spaces1 = spaces1[:-1] stars1 += \"**\"; stars2 += \"*\"; # For middle part if (i == N) : print(spaces1,end=\"\"); print(stars1,end=\"\"); print(spaces1,end=\"\"); print(spaces1,end=\"\"); print(stars2); # For lower part if (i > N) : spaces1 += ' '; stars1 = stars1[:-1]; stars1 = stars1[:-1]; stars2 = stars2[:-1]; print(spaces1,end=\"\"); print(stars1,end=\"\") print(spaces1,end=\"\"); print(spaces1,end=\"\"); print(stars2); # Driver Codeif __name__ == \"__main__\" : N = 5; printFish(N); # This code is contributed by AnkThon", "e": 6906, "s": 5672, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Function to print the pattern of a fish // over N rows static void printFish(int N) { string spaces1 = \"\"; string stars1 = \"*\", stars2 = \"\"; for (int i = 0; i < N; ++i) { spaces1 += ' '; } for (int i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + \"\\n\"); spaces1 = spaces1.Substring(0, spaces1.Length - 1); stars1 += \"**\"; stars2 += \"*\"; } // For middle part if (i == N) { Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + \"\\n\"); } // For lower part if (i > N) { spaces1 += ' '; stars1 = stars1.Substring(0, stars1.Length - 1); stars1 = stars1.Substring(0, stars1.Length - 1); stars2 = stars2.Substring(0, stars2.Length - 1); Console.Write(spaces1 + stars1 + spaces1 + spaces1); Console.Write(stars2 + \"\\n\"); } } } // Driver Code public static void Main() { int N = 5; printFish(N); }} // This code is contributed by Samim Hossain Mondal.", "e": 8327, "s": 6906, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to print the pattern of a fish // over N rows const printFish = (N) => { let spaces1 = \"\", spaces2 = \"\"; let stars1 = \"*\", stars2 = \"\"; for (let i = 0; i < N; ++i) { spaces1 += \" \"; } spaces2 = spaces1; for (let i = 0; i < 2 * N + 1; ++i) { // For upper part if (i < N) { document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); spaces1 = spaces1.substr(0, spaces1.length - 10); stars1 += \"**\"; stars2 += \"*\"; } // For middle part if (i == N) { document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); } // For lower part if (i > N) { spaces1 += \" \"; stars1 = stars1.substr(0, stars1.length - 2); stars2 = stars2.substr(0, stars2.length - 1); document.write(`${spaces1}${stars1}${spaces1}${spaces1}${stars2}<br/>`); } } } // Driver Code let N = 5; printFish(N); // This code is contributed by rakeshsahni </script>", "e": 9570, "s": 8327, "text": null }, { "code": null, "e": 9760, "s": 9573, "text": " * \n *** *\n ***** **\n ******* ***\n ********* ****\n****************\n ********* ****\n ******* ***\n ***** **\n *** *\n * " }, { "code": null, "e": 9805, "s": 9762, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 9815, "s": 9807, "text": "ankthon" }, { "code": null, "e": 9823, "s": 9815, "text": "gfgking" }, { "code": null, "e": 9835, "s": 9823, "text": "rakeshsahni" }, { "code": null, "e": 9845, "s": 9835, "text": "samim2000" }, { "code": null, "e": 9863, "s": 9845, "text": "Pattern Searching" }, { "code": null, "e": 9878, "s": 9863, "text": "Program Output" }, { "code": null, "e": 9896, "s": 9878, "text": "Pattern Searching" } ]
How to center a div within another div? - GeeksforGeeks
09 Jan, 2020 The div tag is used to construct a division or section of an HTML document in which other elements of HTML is placed and that division/section works like a container whose CSS styling can be done as a single unit or javascript can be used to perform various tasks on that container. Syntax: <div> <h3>'This is a div of the web page.>/h3> <p>This is some text in a div element.</p> </div> To get a wide aspect of the div tag usage and its implementation in HTML click here. Example: This example describes how we can place a div inside another div. <!DOCTYPE html><html><meta name="viewport" content="width=device-width, initial-scale=1.0"><head><title>Placing div within a div</title><style>h1 { color:green; text-size:2vw; padding-left : 47px; }h2 { padding-left: 35px; text-size:1vw; } </style> </head><body><h1>GeeksforGeeks</h1> <h2>Placing div within a div</h2><div style="background-color:#4dff4d;width:20%;text-align:center;padding:7px;"><div style="background-color:#33cc33;width:50%;text-align:center;padding:2px;"> <h3 style="font-size:2vw;">Example of div inside a div.</h3> <p style="font-size:2vw;">It has background color = #33cc33.</p> <p style="font-size:2vw;">This is some text in a div element.</p></div></div></body></html> Output: As we can see the inner div container occupied the leftward portion of the inner space. To move the inner div container to the centre of the parent div we have to use the margin property of style attribute. We can adjust the space around any HTML element by this margin property just by providing desired values to it. Now here comes the role of this property in adjusting the inner div. If the margin value is set to 0 i.e., margin : 0, it tells the browser that the top and bottom margin of the HTML element (here inner div) will be 0. Further, if we write the value of margin as margin : 0 auto, it commands the browser to automatically adjust the left and right margin to the same size according to the width of the HTML element. Syntax of inner div: <div style="width:50%;margin:0 auto"> <!-- content of div container --> </div> Example: This example describes how we can center a div inside a div. <!DOCTYPE html><html><meta name="viewport" content="width=device-width, initial-scale=1.0"><head><title>Center alignment of inside div</title><style>h1 { color:green; padding-left : 47px; text-size:2vw; } h2 { padding-left: 11px; text-size:1vw; }</style> </head><body><h1>GeeksforGeeks</h1> <h2>Center alignment of inside div</h2><div style="background-color:#4dff4d;width:20%;text-align:center;padding:7px;"><div style="background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:0 auto"> <h3 style="font-size:2vw;">Example of div inside a div.</h3> <p style="font-size:2vw;">It has background color = #33cc33.</p> <p style="font-size:2vw;">This is some text in a div element.</p></div></div></body></html> Output: You can also provide any value to the first parameter to the margin value to provide some gap from the top and bottom to the HTML element. To adjust the inner div to the center position it is only necessary to write auto in the second parameter. Syntax of inner div: <div style="width:50%;margin:10px auto"> <!-- content of div container --> </div> Example: This example shows how to center a div inside a div with having non zero value for the first parameter of the margin property. <!DOCTYPE html><html><meta name="viewport" content="width=device-width, initial-scale=1.0"><head><title>Center alignment of inside div</title><style>h1 { color:green; padding-left : 47px; text-size:2vw; } h2 { padding-left: 11px; text-size:1vw; }</style> </head><body><h1>GeeksforGeeks</h1> <h2>Center alignment of inside div</h2><div style="background-color:#4dff4d;width:20%;text-align:center;padding:7px;"><div style="background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:10px auto"> <h3 style="font-size:2vw;">Example of div inside a div.</h3> <p style="font-size:2vw;">It has background color = #33cc33.</p> <p style="font-size:2vw;">This is some text in a div element.</p></div></div></body></html> Output: Example: This example describes how we can place 2 div side by side with each div having a center aligned div within itself. <!DOCTYPE html><html><meta name="viewport" content="width=device-width, initial-scale=1.0"><head> <title>2 div example</title><style>h1 { color:green; text-size:2vw; }h2{text-size:1vw;} h1, h2 { padding-left: 100px; }</style> </head> <body><h1>GeeksforGeeks</h1> <h2>Example with 2 div</h2><div style="background-color:#4dff4d;width:25%;text-align:center;padding:7px;float:left;"><div style="background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:0 auto"> <h3 style="font-size:2vw;">Example of div inside a div.</h3> <p style="font-size:2vw;">It has background color = #33cc33.</p> <p style="font-size:2vw;">This is some text in a div element.</p></div></div><div style="background-color:#00cc44;width:25%;text-align:center;padding:7px;float:left;"><div style="background-color:#66ff33;width:50%;text-align:center;padding:2px;margin:0 auto"> <h3 style="font-size:2vw;">Example of div inside a div.</h3> <p style="font-size:2vw;">It has background color = #66ff33.</p> <p style="font-size:2vw;">This is some text in a div element.</p></div></div></body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Basics Picked HTML Technical Scripter 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 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 ? 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": 31393, "s": 31365, "text": "\n09 Jan, 2020" }, { "code": null, "e": 31676, "s": 31393, "text": "The div tag is used to construct a division or section of an HTML document in which other elements of HTML is placed and that division/section works like a container whose CSS styling can be done as a single unit or javascript can be used to perform various tasks on that container." }, { "code": null, "e": 31684, "s": 31676, "text": "Syntax:" }, { "code": null, "e": 31786, "s": 31684, "text": "<div>\n <h3>'This is a div of the web page.>/h3>\n <p>This is some text in a div element.</p>\n</div>\n" }, { "code": null, "e": 31871, "s": 31786, "text": "To get a wide aspect of the div tag usage and its implementation in HTML click here." }, { "code": null, "e": 31946, "s": 31871, "text": "Example: This example describes how we can place a div inside another div." }, { "code": "<!DOCTYPE html><html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><head><title>Placing div within a div</title><style>h1 { color:green; text-size:2vw; padding-left : 47px; }h2 { padding-left: 35px; text-size:1vw; } </style> </head><body><h1>GeeksforGeeks</h1> <h2>Placing div within a div</h2><div style=\"background-color:#4dff4d;width:20%;text-align:center;padding:7px;\"><div style=\"background-color:#33cc33;width:50%;text-align:center;padding:2px;\"> <h3 style=\"font-size:2vw;\">Example of div inside a div.</h3> <p style=\"font-size:2vw;\">It has background color = #33cc33.</p> <p style=\"font-size:2vw;\">This is some text in a div element.</p></div></div></body></html>", "e": 32673, "s": 31946, "text": null }, { "code": null, "e": 32681, "s": 32673, "text": "Output:" }, { "code": null, "e": 33000, "s": 32681, "text": "As we can see the inner div container occupied the leftward portion of the inner space. To move the inner div container to the centre of the parent div we have to use the margin property of style attribute. We can adjust the space around any HTML element by this margin property just by providing desired values to it." }, { "code": null, "e": 33415, "s": 33000, "text": "Now here comes the role of this property in adjusting the inner div. If the margin value is set to 0 i.e., margin : 0, it tells the browser that the top and bottom margin of the HTML element (here inner div) will be 0. Further, if we write the value of margin as margin : 0 auto, it commands the browser to automatically adjust the left and right margin to the same size according to the width of the HTML element." }, { "code": null, "e": 33436, "s": 33415, "text": "Syntax of inner div:" }, { "code": null, "e": 33516, "s": 33436, "text": "<div style=\"width:50%;margin:0 auto\">\n<!-- content of div container -->\n</div>\n" }, { "code": null, "e": 33586, "s": 33516, "text": "Example: This example describes how we can center a div inside a div." }, { "code": "<!DOCTYPE html><html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><head><title>Center alignment of inside div</title><style>h1 { color:green; padding-left : 47px; text-size:2vw; } h2 { padding-left: 11px; text-size:1vw; }</style> </head><body><h1>GeeksforGeeks</h1> <h2>Center alignment of inside div</h2><div style=\"background-color:#4dff4d;width:20%;text-align:center;padding:7px;\"><div style=\"background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:0 auto\"> <h3 style=\"font-size:2vw;\">Example of div inside a div.</h3> <p style=\"font-size:2vw;\">It has background color = #33cc33.</p> <p style=\"font-size:2vw;\">This is some text in a div element.</p></div></div></body></html>", "e": 34337, "s": 33586, "text": null }, { "code": null, "e": 34345, "s": 34337, "text": "Output:" }, { "code": null, "e": 34591, "s": 34345, "text": "You can also provide any value to the first parameter to the margin value to provide some gap from the top and bottom to the HTML element. To adjust the inner div to the center position it is only necessary to write auto in the second parameter." }, { "code": null, "e": 34612, "s": 34591, "text": "Syntax of inner div:" }, { "code": null, "e": 34694, "s": 34612, "text": "<div style=\"width:50%;margin:10px auto\">\n<!-- content of div container -->\n</div>" }, { "code": null, "e": 34830, "s": 34694, "text": "Example: This example shows how to center a div inside a div with having non zero value for the first parameter of the margin property." }, { "code": "<!DOCTYPE html><html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><head><title>Center alignment of inside div</title><style>h1 { color:green; padding-left : 47px; text-size:2vw; } h2 { padding-left: 11px; text-size:1vw; }</style> </head><body><h1>GeeksforGeeks</h1> <h2>Center alignment of inside div</h2><div style=\"background-color:#4dff4d;width:20%;text-align:center;padding:7px;\"><div style=\"background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:10px auto\"> <h3 style=\"font-size:2vw;\">Example of div inside a div.</h3> <p style=\"font-size:2vw;\">It has background color = #33cc33.</p> <p style=\"font-size:2vw;\">This is some text in a div element.</p></div></div></body></html>", "e": 35585, "s": 34830, "text": null }, { "code": null, "e": 35593, "s": 35585, "text": "Output:" }, { "code": null, "e": 35718, "s": 35593, "text": "Example: This example describes how we can place 2 div side by side with each div having a center aligned div within itself." }, { "code": "<!DOCTYPE html><html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><head> <title>2 div example</title><style>h1 { color:green; text-size:2vw; }h2{text-size:1vw;} h1, h2 { padding-left: 100px; }</style> </head> <body><h1>GeeksforGeeks</h1> <h2>Example with 2 div</h2><div style=\"background-color:#4dff4d;width:25%;text-align:center;padding:7px;float:left;\"><div style=\"background-color:#33cc33;width:50%;text-align:center;padding:2px;margin:0 auto\"> <h3 style=\"font-size:2vw;\">Example of div inside a div.</h3> <p style=\"font-size:2vw;\">It has background color = #33cc33.</p> <p style=\"font-size:2vw;\">This is some text in a div element.</p></div></div><div style=\"background-color:#00cc44;width:25%;text-align:center;padding:7px;float:left;\"><div style=\"background-color:#66ff33;width:50%;text-align:center;padding:2px;margin:0 auto\"> <h3 style=\"font-size:2vw;\">Example of div inside a div.</h3> <p style=\"font-size:2vw;\">It has background color = #66ff33.</p> <p style=\"font-size:2vw;\">This is some text in a div element.</p></div></div></body></html>", "e": 36822, "s": 35718, "text": null }, { "code": null, "e": 36830, "s": 36822, "text": "Output:" }, { "code": null, "e": 36967, "s": 36830, "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": 36979, "s": 36967, "text": "HTML-Basics" }, { "code": null, "e": 36986, "s": 36979, "text": "Picked" }, { "code": null, "e": 36991, "s": 36986, "text": "HTML" }, { "code": null, "e": 37010, "s": 36991, "text": "Technical Scripter" }, { "code": null, "e": 37027, "s": 37010, "text": "Web Technologies" }, { "code": null, "e": 37032, "s": 37027, "text": "HTML" }, { "code": null, "e": 37130, "s": 37032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37139, "s": 37130, "text": "Comments" }, { "code": null, "e": 37152, "s": 37139, "text": "Old Comments" }, { "code": null, "e": 37214, "s": 37152, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37264, "s": 37214, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 37324, "s": 37264, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 37372, "s": 37324, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 37433, "s": 37372, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 37489, "s": 37433, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 37522, "s": 37489, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37584, "s": 37522, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37627, "s": 37584, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript - Math max Method
This method returns the largest of zero or more numbers. If no arguments are given, the results is –Infinity. Its syntax is as follows − Math.max(value1, value2, ... valueN ) ; value1, value2, ... valueN : Numbers. Returns the largest of zero or more numbers. Try the following example program. <html> <head> <title>JavaScript Math max() Method</title> </head> <body> <script type = "text/javascript"> var value = Math.max(10, 20, -1, 100); document.write("First Test Value : " + value ); var value = Math.max(-1, -3, -40); document.write("<br />Second Test Value : " + value ); var value = Math.max(0, -1); document.write("<br />Third Test Value : " + value ); var value = Math.max(100); document.write("<br />Fourth Test Value : " + value ); </script> </body> </html> First Test Value : 100 Second Test Value : -1 Third Test Value : 0 Fourth Test Value : 100 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2576, "s": 2466, "text": "This method returns the largest of zero or more numbers. If no arguments are given, the results is –Infinity." }, { "code": null, "e": 2603, "s": 2576, "text": "Its syntax is as follows −" }, { "code": null, "e": 2644, "s": 2603, "text": "Math.max(value1, value2, ... valueN ) ;\n" }, { "code": null, "e": 2682, "s": 2644, "text": "value1, value2, ... valueN : Numbers." }, { "code": null, "e": 2727, "s": 2682, "text": "Returns the largest of zero or more numbers." }, { "code": null, "e": 2762, "s": 2727, "text": "Try the following example program." }, { "code": null, "e": 3389, "s": 2762, "text": "<html> \n <head>\n <title>JavaScript Math max() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var value = Math.max(10, 20, -1, 100);\n document.write(\"First Test Value : \" + value ); \n \n var value = Math.max(-1, -3, -40);\n document.write(\"<br />Second Test Value : \" + value ); \n \n var value = Math.max(0, -1);\n document.write(\"<br />Third Test Value : \" + value ); \n \n var value = Math.max(100);\n document.write(\"<br />Fourth Test Value : \" + value ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3482, "s": 3389, "text": "First Test Value : 100\nSecond Test Value : -1\nThird Test Value : 0\nFourth Test Value : 100 \n" }, { "code": null, "e": 3517, "s": 3482, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3531, "s": 3517, "text": " Anadi Sharma" }, { "code": null, "e": 3565, "s": 3531, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3579, "s": 3565, "text": " Lets Kode It" }, { "code": null, "e": 3614, "s": 3579, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3631, "s": 3614, "text": " Frahaan Hussain" }, { "code": null, "e": 3666, "s": 3631, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3683, "s": 3666, "text": " Frahaan Hussain" }, { "code": null, "e": 3716, "s": 3683, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3744, "s": 3716, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3778, "s": 3744, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3806, "s": 3778, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3813, "s": 3806, "text": " Print" }, { "code": null, "e": 3824, "s": 3813, "text": " Add Notes" } ]
C# Any Method
The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned. Let us see an example. int[] arr = {5, 7, 10, 12, 15, 18, 20}; Now, using Any() method, we will check whether any of the element in the above array is greater than 10 or not. arr.AsQueryable().All(val => val > 5); If any of the element satisfies the condition, then True is returned. Let us see the complete example. Live Demo using System; using System.Linq; class Demo { static void Main() { int[] arr = {5, 7, 10, 12, 15, 18, 20}; // checking if any of the array elements are greater than 10 bool res = arr.AsQueryable().Any(val => val > 10); Console.WriteLine(res); } } True
[ { "code": null, "e": 1162, "s": 1062, "text": "The Any method checks whether any of the element in a sequence satisfy a specific condition or not." }, { "code": null, "e": 1218, "s": 1162, "text": "If any element satisfy the condition, true is returned." }, { "code": null, "e": 1241, "s": 1218, "text": "Let us see an example." }, { "code": null, "e": 1281, "s": 1241, "text": "int[] arr = {5, 7, 10, 12, 15, 18, 20};" }, { "code": null, "e": 1393, "s": 1281, "text": "Now, using Any() method, we will check whether any of the element in the above array is greater than 10 or not." }, { "code": null, "e": 1432, "s": 1393, "text": "arr.AsQueryable().All(val => val > 5);" }, { "code": null, "e": 1502, "s": 1432, "text": "If any of the element satisfies the condition, then True is returned." }, { "code": null, "e": 1535, "s": 1502, "text": "Let us see the complete example." }, { "code": null, "e": 1546, "s": 1535, "text": " Live Demo" }, { "code": null, "e": 1823, "s": 1546, "text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n int[] arr = {5, 7, 10, 12, 15, 18, 20};\n // checking if any of the array elements are greater than 10\n bool res = arr.AsQueryable().Any(val => val > 10);\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1828, "s": 1823, "text": "True" } ]
How do I insert a JPEG image into a Python Tkinter window?
Python provides the Pillow (PIL) package to support, process, and display the images in tkinter applications. A Tkinter application generally supports image files such as, ppm, png, and gif. Let us suppose we want to embed and display a JPEG or JPG image in our application. Tkinter Label widgets are generally used to display the text or images on the window and thus by passing the img value, we can display the JPEG image in the window. #Import required libraries from tkinter import * from PIL import ImageTk, Image #Create an instance of tkinter window win =Tk() #Define the geometry of the window win.geometry("650x400") #Initialize the file name in a variable path = "file.jpg" #Create an object of tkinter ImageTk img = ImageTk.PhotoImage(Image.open(path)) #Create a Label Widget to display the text or Image label = tk.Label(win, image = img) label.pack(fill = "both", expand = "yes") win.mainloop() The code will display a JPEG image that is passed as the image value in the Label widget.
[ { "code": null, "e": 1253, "s": 1062, "text": "Python provides the Pillow (PIL) package to support, process, and display the images in tkinter applications. A Tkinter application generally supports image files such as, ppm, png, and gif." }, { "code": null, "e": 1337, "s": 1253, "text": "Let us suppose we want to embed and display a JPEG or JPG image in our application." }, { "code": null, "e": 1502, "s": 1337, "text": "Tkinter Label widgets are generally used to display the text or images on the window and thus by passing the img value, we can display the JPEG image in the window." }, { "code": null, "e": 1977, "s": 1502, "text": "#Import required libraries\nfrom tkinter import *\nfrom PIL import ImageTk, Image\n\n#Create an instance of tkinter window\nwin =Tk()\n\n#Define the geometry of the window\nwin.geometry(\"650x400\")\n\n#Initialize the file name in a variable\npath = \"file.jpg\"\n\n#Create an object of tkinter ImageTk\nimg = ImageTk.PhotoImage(Image.open(path))\n\n#Create a Label Widget to display the text or Image\nlabel = tk.Label(win, image = img)\nlabel.pack(fill = \"both\", expand = \"yes\")\n\nwin.mainloop()" }, { "code": null, "e": 2067, "s": 1977, "text": "The code will display a JPEG image that is passed as the image value in the Label widget." } ]
How to use ORDER BY field and sort by id in a single MySQL field?
For this, you can use ORDER BY FIELD. Let us first create a table − mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (1.78 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(101,'Chris'); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable values(201,'Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(110,'Adam'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable values(250,'John'); Query OK, 1 row affected (0.33 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------+-------+ | Id | Name | +------+-------+ | 101 | Chris | | 201 | Mike | | 110 | Adam | | 250 | John | +------+-------+ 4 rows in set (0.00 sec) Here is the query to use order by field as well sort by id &miuns; mysql> select *from DemoTable -> order by field(Name,'Mike') desc,Id desc; This will produce the following output − +------+-------+ | Id | Name | +------+-------+ | 201 | Mike | | 250 | John | | 110 | Adam | | 101 | Chris | +------+-------+ 4 rows in set (0.01 sec)
[ { "code": null, "e": 1130, "s": 1062, "text": "For this, you can use ORDER BY FIELD. Let us first create a table −" }, { "code": null, "e": 1251, "s": 1130, "text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (1.78 sec)" }, { "code": null, "e": 1307, "s": 1251, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1648, "s": 1307, "text": "mysql> insert into DemoTable values(101,'Chris');\nQuery OK, 1 row affected (0.38 sec)\nmysql> insert into DemoTable values(201,'Mike');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(110,'Adam');\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into DemoTable values(250,'John');\nQuery OK, 1 row affected (0.33 sec)" }, { "code": null, "e": 1708, "s": 1648, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1739, "s": 1708, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1780, "s": 1739, "text": "This will produce the following output −" }, { "code": null, "e": 1941, "s": 1780, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | Chris |\n| 201 | Mike |\n| 110 | Adam |\n| 250 | John |\n+------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2008, "s": 1941, "text": "Here is the query to use order by field as well sort by id &miuns;" }, { "code": null, "e": 2086, "s": 2008, "text": "mysql> select *from DemoTable\n -> order by field(Name,'Mike') desc,Id desc;" }, { "code": null, "e": 2127, "s": 2086, "text": "This will produce the following output −" }, { "code": null, "e": 2288, "s": 2127, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 201 | Mike |\n| 250 | John |\n| 110 | Adam |\n| 101 | Chris |\n+------+-------+\n4 rows in set (0.01 sec)" } ]
How to explicitly call base class constructor from child class in C#?
Make use of this keyword in c# to call one constructor from another constructor To call a constructor which is present in parent class make use of base keyword To call a constructor which is present in another class make use of base keyword class DemoBase{ public DemoBase(int firstNumber, int secondNumber, int thirdNumber){ System.Console.WriteLine("Base class Constructor"); System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}"); } } class Demo : DemoBase{ public Demo(int firstNumber, int secondNumber, int thirdNumber) : base(firstNumber, secondNumber, thirdNumber){ System.Console.WriteLine("Derived class Constructor"); System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}"); } } class Program{ static void Main(){ Demo obj = new Demo(1, 2, 3); Console.ReadLine(); } } Base class Constructor 1 2 3 Derived class Constructor 1 2 3
[ { "code": null, "e": 1222, "s": 1062, "text": "Make use of this keyword in c# to call one constructor from another constructor To call a constructor which is present in parent class make use of base keyword" }, { "code": null, "e": 1303, "s": 1222, "text": "To call a constructor which is present in another class make use of base keyword" }, { "code": null, "e": 1927, "s": 1303, "text": "class DemoBase{\n public DemoBase(int firstNumber, int secondNumber, int thirdNumber){\n System.Console.WriteLine(\"Base class Constructor\");\n System.Console.WriteLine($\"{firstNumber} {secondNumber} {thirdNumber}\");\n }\n}\nclass Demo : DemoBase{\n public Demo(int firstNumber, int secondNumber, int thirdNumber) : base(firstNumber, secondNumber, thirdNumber){\n System.Console.WriteLine(\"Derived class Constructor\");\n System.Console.WriteLine($\"{firstNumber} {secondNumber} {thirdNumber}\");\n }\n}\nclass Program{\n static void Main(){\n Demo obj = new Demo(1, 2, 3);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1988, "s": 1927, "text": "Base class Constructor\n1 2 3\nDerived class Constructor\n1 2 3" } ]
Filtering Lists in Python. Filtering Methods in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
In this post, we will discuss three methods for list filtering in Python. Specifically, we will walk through how to use list comprehension, generator expressions and the built-in ‘filter()’ method to filter lists in python. Let’s get started! Suppose we have data in a list and we want to extract values or reduce the list based on some criteria. Specifically, let’s consider the following list which contains a list on medical charges with some missing values: medical_charges = ["500", "1000", None, "450", "230", None]print(medical_charges) To start, we can use list comprehension to filter out the ‘None’ values: medical_charges = [n for n in medical_charges if n != None]print(medical_charges) We can also convert the elements of the list to integers with a slight change to the list comprehension: medical_charges = [int(n) for n in medical_charges if n != None]print(medical_charges) Upon converting each element to an integer, we can also filter based off of the magnitude of each integer. Suppose we want to keep charges greater than or equal to $500, we can write the following list comprehension: medical_charges = [n for n in medical_charges if n >= 500]print(medical_charges) If we are dealing with a significant amount of data, which is often the case with medical records, we can filter iteratively using a generator expression. If we want to convert our original list using a generator expression we do the following : charges = (int(n) for n in medical_charges if n != None)print(charges) The main difference in syntax, from list comprehension, being the use of parentheses instead of square brackets. We can now iterate over the generator: for charge in charges: print(charge) There are times when filtering criteria can’t be easily expressed using list comprehension or generator expressions. Let’s consider the example of converting our original list of string valued medical charges into integers and removing missing values: medical_charges = ["500", "1000", None , "450", "230", None] We can define a function that takes a list and tries to convert each element into an integer. When the conversion throws no errors, we return true. When the conversion throws a value error, we use an except statement to catch the error and return false: def convert_and_filter(input_list): try: int(input_list) return True except ValueError: return False We can then use the built-in ‘filter()’ and ‘list()’ methods. The ‘filter()’function creates an iterator and the ‘list()’ method allows us to create a list of results: charges = list(filter(convert_and_filter, medical_charges))print(charges) I’ll stop here but feel free to play around with the examples above. For example, you can try changing the filtering conditions in the list comprehension example to only include charges less than or equal to $500. To summarize, in this post we discussed four methods for list filtering in Python. We discussed list comprehension which is useful for its readability. We also discussed generator expressions which we use if we want to avoid generating large results from large data sets. Finally, we discussed using the built-in ‘filter()’ and ‘list()’ methods, along with a custom function, to filter lists. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 396, "s": 172, "text": "In this post, we will discuss three methods for list filtering in Python. Specifically, we will walk through how to use list comprehension, generator expressions and the built-in ‘filter()’ method to filter lists in python." }, { "code": null, "e": 415, "s": 396, "text": "Let’s get started!" }, { "code": null, "e": 634, "s": 415, "text": "Suppose we have data in a list and we want to extract values or reduce the list based on some criteria. Specifically, let’s consider the following list which contains a list on medical charges with some missing values:" }, { "code": null, "e": 716, "s": 634, "text": "medical_charges = [\"500\", \"1000\", None, \"450\", \"230\", None]print(medical_charges)" }, { "code": null, "e": 789, "s": 716, "text": "To start, we can use list comprehension to filter out the ‘None’ values:" }, { "code": null, "e": 871, "s": 789, "text": "medical_charges = [n for n in medical_charges if n != None]print(medical_charges)" }, { "code": null, "e": 976, "s": 871, "text": "We can also convert the elements of the list to integers with a slight change to the list comprehension:" }, { "code": null, "e": 1063, "s": 976, "text": "medical_charges = [int(n) for n in medical_charges if n != None]print(medical_charges)" }, { "code": null, "e": 1280, "s": 1063, "text": "Upon converting each element to an integer, we can also filter based off of the magnitude of each integer. Suppose we want to keep charges greater than or equal to $500, we can write the following list comprehension:" }, { "code": null, "e": 1361, "s": 1280, "text": "medical_charges = [n for n in medical_charges if n >= 500]print(medical_charges)" }, { "code": null, "e": 1607, "s": 1361, "text": "If we are dealing with a significant amount of data, which is often the case with medical records, we can filter iteratively using a generator expression. If we want to convert our original list using a generator expression we do the following :" }, { "code": null, "e": 1678, "s": 1607, "text": "charges = (int(n) for n in medical_charges if n != None)print(charges)" }, { "code": null, "e": 1830, "s": 1678, "text": "The main difference in syntax, from list comprehension, being the use of parentheses instead of square brackets. We can now iterate over the generator:" }, { "code": null, "e": 1870, "s": 1830, "text": "for charge in charges: print(charge)" }, { "code": null, "e": 2122, "s": 1870, "text": "There are times when filtering criteria can’t be easily expressed using list comprehension or generator expressions. Let’s consider the example of converting our original list of string valued medical charges into integers and removing missing values:" }, { "code": null, "e": 2183, "s": 2122, "text": "medical_charges = [\"500\", \"1000\", None , \"450\", \"230\", None]" }, { "code": null, "e": 2437, "s": 2183, "text": "We can define a function that takes a list and tries to convert each element into an integer. When the conversion throws no errors, we return true. When the conversion throws a value error, we use an except statement to catch the error and return false:" }, { "code": null, "e": 2565, "s": 2437, "text": "def convert_and_filter(input_list): try: int(input_list) return True except ValueError: return False" }, { "code": null, "e": 2733, "s": 2565, "text": "We can then use the built-in ‘filter()’ and ‘list()’ methods. The ‘filter()’function creates an iterator and the ‘list()’ method allows us to create a list of results:" }, { "code": null, "e": 2807, "s": 2733, "text": "charges = list(filter(convert_and_filter, medical_charges))print(charges)" }, { "code": null, "e": 3021, "s": 2807, "text": "I’ll stop here but feel free to play around with the examples above. For example, you can try changing the filtering conditions in the list comprehension example to only include charges less than or equal to $500." } ]
How to call an activity method from a fragment in Android App using Kotlin.
This example demonstrates how to call an activity method from a fragment in an Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frameLayout, SampleFragment()).commit() } fun fragmentMethod() { Toast.makeText(this@MainActivity, "Method called From Fragment", Toast.LENGTH_LONG).show() } } Step 4 − Create a Fragment Activity and add the following code <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SampleFragment"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Calling a simple method from Fragment" android:textAlignment="center" android:textColor="@android:color/background_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class SampleFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_sample, container, false) (activity as MainActivity?)!!.fragmentMethod() return view } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1167, "s": 1062, "text": "This example demonstrates how to call an activity method from a fragment in an Android App using Kotlin." }, { "code": null, "e": 1296, "s": 1167, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1361, "s": 1296, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2197, "s": 1361, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <FrameLayout\n android:id=\"@+id/frameLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>" }, { "code": null, "e": 2252, "s": 2197, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2902, "s": 2252, "text": "import android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val fragmentManager = supportFragmentManager\n val fragmentTransaction = fragmentManager.beginTransaction()\n fragmentTransaction.replace(R.id.frameLayout, SampleFragment()).commit()\n }\n fun fragmentMethod() {\n Toast.makeText(this@MainActivity, \"Method called From Fragment\",\n Toast.LENGTH_LONG).show()\n }\n}" }, { "code": null, "e": 2965, "s": 2902, "text": "Step 4 − Create a Fragment Activity and add the following code" }, { "code": null, "e": 3620, "s": 2965, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".SampleFragment\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Calling a simple method from Fragment\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 4101, "s": 3620, "text": "import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.Fragment\nclass SampleFragment : Fragment() {\n override fun onCreateView(\n inflater: LayoutInflater,\n container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n val view: View = inflater.inflate(R.layout.fragment_sample, container, false)\n (activity as MainActivity?)!!.fragmentMethod()\n return view\n }\n}" }, { "code": null, "e": 4156, "s": 4101, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4823, "s": 4156, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5171, "s": 4823, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Bash program to check if the Number is a Palindrome?
To check whether a number is palindrome or not, we have to reverse the number, and then if the actual number and the reversed number are same, then this is palindrome. In Bash, performing the reverse operation is very easy. We have to use the ‘rev’ command to do that. Let us see the program to understand clearly. #!/bin/bash # GNU bash Script n=12321 rev=$(echo $n | rev) if [ $n -eq $rev ]; then echo "Number is palindrome" else echo "Number is not palindrome" fi Number is palindrome
[ { "code": null, "e": 1377, "s": 1062, "text": "To check whether a number is palindrome or not, we have to reverse the number, and then if the actual number and the reversed number are same, then this is palindrome. In Bash, performing the reverse operation is very easy. We have to use the ‘rev’ command to do that. Let us see the program to understand clearly." }, { "code": null, "e": 1535, "s": 1377, "text": "#!/bin/bash\n# GNU bash Script\nn=12321\nrev=$(echo $n | rev)\nif [ $n -eq $rev ]; then\n echo \"Number is palindrome\"\nelse\n echo \"Number is not palindrome\"\nfi" }, { "code": null, "e": 1556, "s": 1535, "text": "Number is palindrome" } ]
How to make bar and hbar charts with labels using matplotlib | by Jacob Toftgaard Rasmussen | Towards Data Science
The first time I made a bar chart I could not immediately figure out how to add labels to the bars. Especially the horizontal bar charts were troublesome for me. So don’t worry if you also cannot make it work. In this post you will learn how this is done along with some tips and tricks for styling the diagram. NOTE: If you only need to see how to add labels you can skip to the section: Creating bar charts with labels. I have included all the code that I have written for you to copy if you want to type along as you read, as well as detailed explanations of how the code works. To allow me to teach you how to make bar charts with labels I needed some data to work with. Therefore, I decided to grab some game data from the online game League of Legends. This makes the guide more fun for fans of the game, (myself included). The first part of the post is a walk through for how I clean up the data to get it into my preferred format. I encourage you to read that part as well as it teaches you a way to convert data from JSON format to a Pandas DataFrame. The post has the following structure: Introduction Preparing the data (JSON to Pandas DataFrame) Creating bar charts with labels Summary and goodbyes I have a JSON file that contains the base stats (characteristics) of all the champions (playable characters) in League of Legends. You can access the data file here. The data looks like this (see screenshot): In total, there are 153 champions that all include the same keys in their dictionaries. Ultimately we will make a bar chart that shows the starting hp (hit points) of champions, to get an overview of which champions start out with the most health. If you are curious about other statistics it will be super easy for you to change what the bar chart shows, for example you might be interested in seeing which champions have the most ad (attack damage). Next I would like to convert this data from the JSON format that it is currently in to a Pandas DataFrame instead. I encourage you to try to code along as this will give you the best understanding! Learning by doing you know. import pandas as pdimport matplotlib.pyplot as pltimport json I start out by importing the necessary libraries that we will use. Pandas allows us to make DataFrames which is a nice structure to work with when doing data science. Matplotlib.pyplot will be used to make the charts. json will allow you to load the data from the JSON file into memory for us to work with. with open('champ_stats.json') as f: data = json.load(f)champion = data['Aatrox']stat_names = list(champion.keys())columns = ['champ'] + stat_namesdf = pd.DataFrame() I open the data file and load it into the variable called data. Next I would like to have a list that contains the names of all the different stats,(statistics/characteristics of a champion), as this will be the column names for the finished DataFrame. The list of stats is included in all the champion dictionaries in the data, because of this we just need to dive into one of them and take the keys from that dictionary. We access the 'Aatrox' key as this is the first champion the the data. This gives us the the corresponding value which we save to the champion variable. This value is another dictionary where all the keys are the names that we are looking for, therefore we use the .keys() function to get its keys and the returned value is transformed to a list as the function was called inside the list() function. If this step confuses you I have written another guide that explains how to access data in python dictionaries that you can find here. The column names for the DataFrame are going to be 'champ' for the first column which will contain all the names of the champions, and the other columns will be named after the items in stat_names. We save this to the variable columns. Finally we use pd.DataFrame() to create an empty DataFrame that we save to the variable df. for name, stats in data.items(): values = [stats[x] for x in columns[1:]] row = pd.DataFrame([[name] + values], columns=columns) df = df.append(row)df.head() From the previous step we had an empty DataFrame and it is now time to populate it with rows of data, where each row represents a champion. We now make a for statement that loops through all the key value pairs in the data dictionary, (name is the key and stats is the value). We want a list of all the stat values and to get that I use list comprehension and save the resulting list to the variable values. The list comprehension works like this: For every name (x) in columns[1:] we take that name and use it as the key to access the corresponding value from stats, and that value is added to the list. Next we make a new DataFrame that we save to the variable row. This DataFrame is instantiated with two parameters. Firstly, a list inside a list, where the inner list contains the name and all the values for the current champion. Secondly, the formal columns= attribute is set to our list variable also called columns, this will set the names of the columns in the DataFrame as we want them.Next we append the row to the main DataFrame that we called df, this returns a new DataFrame with which we override the previous df. Finally, we call the head() method on df to display the first rows of the DataFrame. If you have coded along you should now get the following output: The data is now nicely formatted as a DataFrame and in the next step we will finally create the bar charts and add labels. df_sorted_by_hp = df.sort_values('hp', ascending=False)x = df_sorted_by_hp['champ'][:15]y = df_sorted_by_hp['hp'][:15] To improve the diagram I have chosen to sort the rows in the DataFrame by the 'hp' value, and ascending=False sorts the values in descending order. Afterwards, we save the champ column to the variable named x and similarly the hp values to the variable y. To make sure that the diagram is not too cluttered I have chosen only to include the first 15 champions this is done with the [:15] suffix. fig, ax = plt.subplots(figsize=(20,4))bars = ax.bar(x, y, width=0.5) We use plt.subplots(figsize=(20,4)) to create a figure object and an axes object, which are saved to the variables fig and ax. We set the figure size to be 20 by 4 inches, this might not be the absolute best size, but you can play around with the numbers until you find out what size suits your chart best. ax.bar(x, y, width=0.5) creates the bar chart with our x and y values and a width of 0.5, again, you can try out different sizes between 0 and 1 for the width. I save the returned object in the variable bars which we will use shortly. The code will produce the following chart, (Just a part of it to make it fit better on Medium): ... Not very cool First of all, the height difference for the bars is super hard to distinguish, and secondly, it is impossible to read the exact height of each of the bars. This is where the labels will be useful! Lets add them now! Note: Append this following code snippet to the previous one. for bar in bars: height = bar.get_height() label_x_pos = bar.get_x() + bar.get_width() / 2 ax.text(label_x_pos, height, s=f'{height}', ha='center', va='bottom') We can loop through the bars variable to go over every bar in the chart. We save the height of each bar to a variable called height by getting it from the bar.get_height() function. Next we need the x position for the label for the current bar in the loop. We get this position from the bar.get_x() function and add the width of the bar divided by 2 to get the x value for the center of the bar. Finally, we use ax.text(label_x_pos, height, s=f'{height}', ha='center') to create the label/text. This function takes a value for the x position and one for the y position, then we give it the string that it will display, which in this case is the height of the bar. Lastly ha='center' further helps align the label at the center of the bar, and va='bottom' places the label just above the bar. This will produce the following chart, (Just a part of it to make it fit better on Medium): Yes! Now we have labels for the bars displaying their individual height! This is clearly better, but it can still be improved upon. I think that the names under the bars are a bit hard to read due to their size. Also I would like a title for the chart along with descriptions for the axes. Furthermore, there is no point in having the y axis start from 0. Finally, I think the diagram could be spiced up with some color! Note: Append this following code snippet to the previous one. for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(14)for bar in bars[::2]: bar.set_color('r')plt.title('The 15 champions with the most HP')plt.xlabel('Champion name')plt.ylabel('Starting hp')plt.ylim([550,650])plt.show() You can set the font size for each tick by looping over the ticks returned from ax.xaxis.get_major_ticks() and provide a font size with tick.label.set_fontsize(14). Similarly you can access every second bar with for bar in bars[::2]: and set the color with bar.set_color('r'). The title, x label and y label can be set with their corresponding functions. Finally, you can limit the y axis (same goes for the x axis), with plt.ylim([550, 650]). I find that starting with 550 and ending with 650 worked will for this diagram. plt.show() will show the finished bar chart, (Just a part of it to make it fit better on Medium): A big improvement I think! To make a horizontal bar chart there is very little that we have to change. Because of this I will show the code in a single snippet, and highlight the changes in bold. Also, keep in mind that the data is the same as before and because of this we still have all the names in the x variable and all the hp values in the y variable. fig, ax = plt.subplots(figsize=(4, 10))bars = ax.barh(x,y, 0.5)for bar in bars: width = bar.get_width() #Previously we got the height label_y_pos = bar.get_y() + bar.get_height() / 2 ax.text(width, label_y_pos, s=f'{width}', va='center')for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14)for bar in bars[::2]: bar.set_color('r')plt.title('The 15 champions with the most HP')plt.xlabel('Starting hp')plt.ylabel('Champion name')plt.xlim([550, 650])plt.show() Same as before we create the figure and axes objects and set the size, however, this time a size of (4, 10) works better, (taller than wide). To make a horizontal bar chart we use ax.barh() instead of ax.bar(). Next, instead of getting the height of each bar we get the width. We need to get the y position of the bars using bar.get_y() instead of the x position, and we add the height of the bar divided by 2, (notice that height has a different meaning here compared to before). We again set the label for the bar with ax.text(), however, we use width for the x position and for the string to be displayed. Additionally, we use the argument va='center', this helps to place the label at the center of the bar. Try removing it to see the difference. For the ticks we simply change the size of the y ticks instead of the x ticks. Finally, you have to switch the labels for the axes as well as limiting the x axis opposed to the y axis.The result: Voilá you now know how to make both vertical and horizontal bar charts, as well as adding labels to make them more readable. If you followed the whole guide you have now created a small project where you both transformed JSON data into a Pandas DataFrame and afterwards created bar charts with labels. Personally I prefer the horizontal bar chart as I find it easier to read in this case. Remember that you can explore the data further if you are interested. Try finding out which champion has the least hp, or show more champions on your charts. If you have any questions, comments or tips for improving the post, please do not hesitate to reach out to me! Thank you for taking the time to read this post, I hope you learned something useful! Keep learning! — Jacob Toftgaard Rasmussen
[ { "code": null, "e": 483, "s": 171, "text": "The first time I made a bar chart I could not immediately figure out how to add labels to the bars. Especially the horizontal bar charts were troublesome for me. So don’t worry if you also cannot make it work. In this post you will learn how this is done along with some tips and tricks for styling the diagram." }, { "code": null, "e": 753, "s": 483, "text": "NOTE: If you only need to see how to add labels you can skip to the section: Creating bar charts with labels. I have included all the code that I have written for you to copy if you want to type along as you read, as well as detailed explanations of how the code works." }, { "code": null, "e": 1232, "s": 753, "text": "To allow me to teach you how to make bar charts with labels I needed some data to work with. Therefore, I decided to grab some game data from the online game League of Legends. This makes the guide more fun for fans of the game, (myself included). The first part of the post is a walk through for how I clean up the data to get it into my preferred format. I encourage you to read that part as well as it teaches you a way to convert data from JSON format to a Pandas DataFrame." }, { "code": null, "e": 1270, "s": 1232, "text": "The post has the following structure:" }, { "code": null, "e": 1283, "s": 1270, "text": "Introduction" }, { "code": null, "e": 1329, "s": 1283, "text": "Preparing the data (JSON to Pandas DataFrame)" }, { "code": null, "e": 1361, "s": 1329, "text": "Creating bar charts with labels" }, { "code": null, "e": 1382, "s": 1361, "text": "Summary and goodbyes" }, { "code": null, "e": 1591, "s": 1382, "text": "I have a JSON file that contains the base stats (characteristics) of all the champions (playable characters) in League of Legends. You can access the data file here. The data looks like this (see screenshot):" }, { "code": null, "e": 1679, "s": 1591, "text": "In total, there are 153 champions that all include the same keys in their dictionaries." }, { "code": null, "e": 2043, "s": 1679, "text": "Ultimately we will make a bar chart that shows the starting hp (hit points) of champions, to get an overview of which champions start out with the most health. If you are curious about other statistics it will be super easy for you to change what the bar chart shows, for example you might be interested in seeing which champions have the most ad (attack damage)." }, { "code": null, "e": 2158, "s": 2043, "text": "Next I would like to convert this data from the JSON format that it is currently in to a Pandas DataFrame instead." }, { "code": null, "e": 2269, "s": 2158, "text": "I encourage you to try to code along as this will give you the best understanding! Learning by doing you know." }, { "code": null, "e": 2331, "s": 2269, "text": "import pandas as pdimport matplotlib.pyplot as pltimport json" }, { "code": null, "e": 2638, "s": 2331, "text": "I start out by importing the necessary libraries that we will use. Pandas allows us to make DataFrames which is a nice structure to work with when doing data science. Matplotlib.pyplot will be used to make the charts. json will allow you to load the data from the JSON file into memory for us to work with." }, { "code": null, "e": 2805, "s": 2638, "text": "with open('champ_stats.json') as f: data = json.load(f)champion = data['Aatrox']stat_names = list(champion.keys())columns = ['champ'] + stat_namesdf = pd.DataFrame()" }, { "code": null, "e": 3764, "s": 2805, "text": "I open the data file and load it into the variable called data. Next I would like to have a list that contains the names of all the different stats,(statistics/characteristics of a champion), as this will be the column names for the finished DataFrame. The list of stats is included in all the champion dictionaries in the data, because of this we just need to dive into one of them and take the keys from that dictionary. We access the 'Aatrox' key as this is the first champion the the data. This gives us the the corresponding value which we save to the champion variable. This value is another dictionary where all the keys are the names that we are looking for, therefore we use the .keys() function to get its keys and the returned value is transformed to a list as the function was called inside the list() function. If this step confuses you I have written another guide that explains how to access data in python dictionaries that you can find here." }, { "code": null, "e": 4092, "s": 3764, "text": "The column names for the DataFrame are going to be 'champ' for the first column which will contain all the names of the champions, and the other columns will be named after the items in stat_names. We save this to the variable columns. Finally we use pd.DataFrame() to create an empty DataFrame that we save to the variable df." }, { "code": null, "e": 4253, "s": 4092, "text": "for name, stats in data.items(): values = [stats[x] for x in columns[1:]] row = pd.DataFrame([[name] + values], columns=columns) df = df.append(row)df.head()" }, { "code": null, "e": 4858, "s": 4253, "text": "From the previous step we had an empty DataFrame and it is now time to populate it with rows of data, where each row represents a champion. We now make a for statement that loops through all the key value pairs in the data dictionary, (name is the key and stats is the value). We want a list of all the stat values and to get that I use list comprehension and save the resulting list to the variable values. The list comprehension works like this: For every name (x) in columns[1:] we take that name and use it as the key to access the corresponding value from stats, and that value is added to the list." }, { "code": null, "e": 5382, "s": 4858, "text": "Next we make a new DataFrame that we save to the variable row. This DataFrame is instantiated with two parameters. Firstly, a list inside a list, where the inner list contains the name and all the values for the current champion. Secondly, the formal columns= attribute is set to our list variable also called columns, this will set the names of the columns in the DataFrame as we want them.Next we append the row to the main DataFrame that we called df, this returns a new DataFrame with which we override the previous df." }, { "code": null, "e": 5532, "s": 5382, "text": "Finally, we call the head() method on df to display the first rows of the DataFrame. If you have coded along you should now get the following output:" }, { "code": null, "e": 5655, "s": 5532, "text": "The data is now nicely formatted as a DataFrame and in the next step we will finally create the bar charts and add labels." }, { "code": null, "e": 5774, "s": 5655, "text": "df_sorted_by_hp = df.sort_values('hp', ascending=False)x = df_sorted_by_hp['champ'][:15]y = df_sorted_by_hp['hp'][:15]" }, { "code": null, "e": 6170, "s": 5774, "text": "To improve the diagram I have chosen to sort the rows in the DataFrame by the 'hp' value, and ascending=False sorts the values in descending order. Afterwards, we save the champ column to the variable named x and similarly the hp values to the variable y. To make sure that the diagram is not too cluttered I have chosen only to include the first 15 champions this is done with the [:15] suffix." }, { "code": null, "e": 6239, "s": 6170, "text": "fig, ax = plt.subplots(figsize=(20,4))bars = ax.bar(x, y, width=0.5)" }, { "code": null, "e": 6781, "s": 6239, "text": "We use plt.subplots(figsize=(20,4)) to create a figure object and an axes object, which are saved to the variables fig and ax. We set the figure size to be 20 by 4 inches, this might not be the absolute best size, but you can play around with the numbers until you find out what size suits your chart best. ax.bar(x, y, width=0.5) creates the bar chart with our x and y values and a width of 0.5, again, you can try out different sizes between 0 and 1 for the width. I save the returned object in the variable bars which we will use shortly." }, { "code": null, "e": 6877, "s": 6781, "text": "The code will produce the following chart, (Just a part of it to make it fit better on Medium):" }, { "code": null, "e": 6895, "s": 6877, "text": "... Not very cool" }, { "code": null, "e": 7111, "s": 6895, "text": "First of all, the height difference for the bars is super hard to distinguish, and secondly, it is impossible to read the exact height of each of the bars. This is where the labels will be useful! Lets add them now!" }, { "code": null, "e": 7173, "s": 7111, "text": "Note: Append this following code snippet to the previous one." }, { "code": null, "e": 7338, "s": 7173, "text": "for bar in bars: height = bar.get_height() label_x_pos = bar.get_x() + bar.get_width() / 2 ax.text(label_x_pos, height, s=f'{height}', ha='center', va='bottom')" }, { "code": null, "e": 7734, "s": 7338, "text": "We can loop through the bars variable to go over every bar in the chart. We save the height of each bar to a variable called height by getting it from the bar.get_height() function. Next we need the x position for the label for the current bar in the loop. We get this position from the bar.get_x() function and add the width of the bar divided by 2 to get the x value for the center of the bar." }, { "code": null, "e": 8130, "s": 7734, "text": "Finally, we use ax.text(label_x_pos, height, s=f'{height}', ha='center') to create the label/text. This function takes a value for the x position and one for the y position, then we give it the string that it will display, which in this case is the height of the bar. Lastly ha='center' further helps align the label at the center of the bar, and va='bottom' places the label just above the bar." }, { "code": null, "e": 8222, "s": 8130, "text": "This will produce the following chart, (Just a part of it to make it fit better on Medium):" }, { "code": null, "e": 8354, "s": 8222, "text": "Yes! Now we have labels for the bars displaying their individual height! This is clearly better, but it can still be improved upon." }, { "code": null, "e": 8643, "s": 8354, "text": "I think that the names under the bars are a bit hard to read due to their size. Also I would like a title for the chart along with descriptions for the axes. Furthermore, there is no point in having the y axis start from 0. Finally, I think the diagram could be spiced up with some color!" }, { "code": null, "e": 8705, "s": 8643, "text": "Note: Append this following code snippet to the previous one." }, { "code": null, "e": 8942, "s": 8705, "text": "for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(14)for bar in bars[::2]: bar.set_color('r')plt.title('The 15 champions with the most HP')plt.xlabel('Champion name')plt.ylabel('Starting hp')plt.ylim([550,650])plt.show()" }, { "code": null, "e": 9466, "s": 8942, "text": "You can set the font size for each tick by looping over the ticks returned from ax.xaxis.get_major_ticks() and provide a font size with tick.label.set_fontsize(14). Similarly you can access every second bar with for bar in bars[::2]: and set the color with bar.set_color('r'). The title, x label and y label can be set with their corresponding functions. Finally, you can limit the y axis (same goes for the x axis), with plt.ylim([550, 650]). I find that starting with 550 and ending with 650 worked will for this diagram." }, { "code": null, "e": 9564, "s": 9466, "text": "plt.show() will show the finished bar chart, (Just a part of it to make it fit better on Medium):" }, { "code": null, "e": 9591, "s": 9564, "text": "A big improvement I think!" }, { "code": null, "e": 9922, "s": 9591, "text": "To make a horizontal bar chart there is very little that we have to change. Because of this I will show the code in a single snippet, and highlight the changes in bold. Also, keep in mind that the data is the same as before and because of this we still have all the names in the x variable and all the hp values in the y variable." }, { "code": null, "e": 10400, "s": 9922, "text": "fig, ax = plt.subplots(figsize=(4, 10))bars = ax.barh(x,y, 0.5)for bar in bars: width = bar.get_width() #Previously we got the height label_y_pos = bar.get_y() + bar.get_height() / 2 ax.text(width, label_y_pos, s=f'{width}', va='center')for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14)for bar in bars[::2]: bar.set_color('r')plt.title('The 15 champions with the most HP')plt.xlabel('Starting hp')plt.ylabel('Champion name')plt.xlim([550, 650])plt.show()" }, { "code": null, "e": 10881, "s": 10400, "text": "Same as before we create the figure and axes objects and set the size, however, this time a size of (4, 10) works better, (taller than wide). To make a horizontal bar chart we use ax.barh() instead of ax.bar(). Next, instead of getting the height of each bar we get the width. We need to get the y position of the bars using bar.get_y() instead of the x position, and we add the height of the bar divided by 2, (notice that height has a different meaning here compared to before)." }, { "code": null, "e": 11151, "s": 10881, "text": "We again set the label for the bar with ax.text(), however, we use width for the x position and for the string to be displayed. Additionally, we use the argument va='center', this helps to place the label at the center of the bar. Try removing it to see the difference." }, { "code": null, "e": 11347, "s": 11151, "text": "For the ticks we simply change the size of the y ticks instead of the x ticks. Finally, you have to switch the labels for the axes as well as limiting the x axis opposed to the y axis.The result:" }, { "code": null, "e": 11473, "s": 11347, "text": "Voilá you now know how to make both vertical and horizontal bar charts, as well as adding labels to make them more readable." }, { "code": null, "e": 11650, "s": 11473, "text": "If you followed the whole guide you have now created a small project where you both transformed JSON data into a Pandas DataFrame and afterwards created bar charts with labels." }, { "code": null, "e": 11895, "s": 11650, "text": "Personally I prefer the horizontal bar chart as I find it easier to read in this case. Remember that you can explore the data further if you are interested. Try finding out which champion has the least hp, or show more champions on your charts." }, { "code": null, "e": 12006, "s": 11895, "text": "If you have any questions, comments or tips for improving the post, please do not hesitate to reach out to me!" }, { "code": null, "e": 12092, "s": 12006, "text": "Thank you for taking the time to read this post, I hope you learned something useful!" } ]
What is setTimeout() Method in javascript?
This is one of the many timing events. The window object allows the execution of code at specified time intervals. This object has provided SetTimeout() to execute a function after a certain amount of time. It takes two parameters as arguments. One is the function and the other is the time that specifies the interval after which the function should be executed. window.setTimeout(function, milliseconds); In the following example, the time passed to the setTimeout() function is 2 seconds. Therefore the function will be executed after two secs and display the output as shown. Live Demo <html> <body> <p>wait 2 seconds.</p> <script> setTimeout(function(){ document.write("Tutorix is the best e-learning platform"); }, 2000); </script> </body> </html> wait 2 seconds Tutorix is the best e-learning platform In the following example, the time passed to the setTimeout() function is 3 seconds. Therefore the function will be executed after three secs and display the output as shown. Live Demo <html> <body> <p id = "time"></p> <script> setTimeout(function(){ document.getElementById("time").innerHTML = "Tutorix is the product of Tutorialspoint"; }, 3000); </script> </body> </html> Tutorix is the product of Tutorialspoint.
[ { "code": null, "e": 1426, "s": 1062, "text": "This is one of the many timing events. The window object allows the execution of code at specified time intervals. This object has provided SetTimeout() to execute a function after a certain amount of time. It takes two parameters as arguments. One is the function and the other is the time that specifies the interval after which the function should be executed." }, { "code": null, "e": 1469, "s": 1426, "text": "window.setTimeout(function, milliseconds);" }, { "code": null, "e": 1642, "s": 1469, "text": "In the following example, the time passed to the setTimeout() function is 2 seconds. Therefore the function will be executed after two secs and display the output as shown." }, { "code": null, "e": 1652, "s": 1642, "text": "Live Demo" }, { "code": null, "e": 1828, "s": 1652, "text": "<html>\n<body>\n<p>wait 2 seconds.</p>\n<script>\n setTimeout(function(){\n document.write(\"Tutorix is the best e-learning platform\");\n }, 2000);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1883, "s": 1828, "text": "wait 2 seconds\nTutorix is the best e-learning platform" }, { "code": null, "e": 2058, "s": 1883, "text": "In the following example, the time passed to the setTimeout() function is 3 seconds. Therefore the function will be executed after three secs and display the output as shown." }, { "code": null, "e": 2068, "s": 2058, "text": "Live Demo" }, { "code": null, "e": 2270, "s": 2068, "text": "<html>\n<body>\n<p id = \"time\"></p>\n<script>\n setTimeout(function(){\n document.getElementById(\"time\").innerHTML = \"Tutorix is the product of Tutorialspoint\";\n }, 3000);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2312, "s": 2270, "text": "Tutorix is the product of Tutorialspoint." } ]
C# Substring() Method
The Substring() method in C# is used to retrieve a substring from this instance. The substring starts at a specified character position and continues to the end of the string. The syntax is as follows - public string Substring (int begnIndex); public string Substring (int begnIndex, int len); Above, begnIndex is the zero-based starting character position of a substring in this instance. The len parameter is the number of the substring to retrieve Let us now see an example - Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "Katherine"; string str2 = "PQRS"; Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant()); Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4)); Console.WriteLine("\nString2 = "+str2); Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant()); Console.WriteLine("String2 Substring from index2 = " + str2.Substring(2)); } } String1 = Katherine String1 ToUpperInvariant = KATHERINE String1 Substring from index4 = erine String2 = PQRS String2 ToUpperInvariant = pqrs String2 Substring from index2 = RS Let us now see another example - Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "Notebook"; string str2 = "Ultrabook"; Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant()); Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4)); Console.WriteLine("\nString2 = "+str2); Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant()); Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5)); } } String1 = Notebook String1 ToUpperInvariant = NOTEBOOK String1 Substring from index4 = book String2 = Ultrabook String2 ToUpperInvariant = ultrabook String2 Substring from index2 = Ultra
[ { "code": null, "e": 1238, "s": 1062, "text": "The Substring() method in C# is used to retrieve a substring from this instance. The substring starts at a specified character position and continues to the end of the string." }, { "code": null, "e": 1265, "s": 1238, "text": "The syntax is as follows -" }, { "code": null, "e": 1356, "s": 1265, "text": "public string Substring (int begnIndex);\npublic string Substring (int begnIndex, int len);" }, { "code": null, "e": 1513, "s": 1356, "text": "Above, begnIndex is the zero-based starting character position of a substring in this instance. The len parameter is the number of the substring to retrieve" }, { "code": null, "e": 1541, "s": 1513, "text": "Let us now see an example -" }, { "code": null, "e": 1552, "s": 1541, "text": " Live Demo" }, { "code": null, "e": 2110, "s": 1552, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"Katherine\";\n string str2 = \"PQRS\";\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String1 ToUpperInvariant = \"+str1.ToUpperInvariant());\n Console.WriteLine(\"String1 Substring from index4 = \" + str1.Substring(4));\n Console.WriteLine(\"\\nString2 = \"+str2);\n Console.WriteLine(\"String2 ToUpperInvariant = \"+str2.ToLowerInvariant());\n Console.WriteLine(\"String2 Substring from index2 = \" + str2.Substring(2));\n }\n}" }, { "code": null, "e": 2287, "s": 2110, "text": "String1 = Katherine\nString1 ToUpperInvariant = KATHERINE\nString1 Substring from index4 = erine\nString2 = PQRS\nString2 ToUpperInvariant = pqrs\nString2 Substring from index2 = RS" }, { "code": null, "e": 2320, "s": 2287, "text": "Let us now see another example -" }, { "code": null, "e": 2331, "s": 2320, "text": " Live Demo" }, { "code": null, "e": 2899, "s": 2331, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"Notebook\";\n string str2 = \"Ultrabook\";\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String1 ToUpperInvariant = \"+str1.ToUpperInvariant());\n Console.WriteLine(\"String1 Substring from index4 = \" + str1.Substring(4, 4));\n Console.WriteLine(\"\\nString2 = \"+str2);\n Console.WriteLine(\"String2 ToUpperInvariant = \"+str2.ToLowerInvariant());\n Console.WriteLine(\"String2 Substring from index2 = \" + str2.Substring(0, 5));\n }\n}" }, { "code": null, "e": 3086, "s": 2899, "text": "String1 = Notebook\nString1 ToUpperInvariant = NOTEBOOK\nString1 Substring from index4 = book\nString2 = Ultrabook\nString2 ToUpperInvariant = ultrabook\nString2 Substring from index2 = Ultra" } ]
Perl | Use of Hash bang or Shebang line - GeeksforGeeks
11 Jul, 2019 Practical Extraction and Reporting Language or Perl is an interpreter based language. Hash-bangs or shebangs are useful when we are executing Perl scripts on Unix-like systems such as Linux and Mac OSX. A Hashbang line is the first line of a Perl program and is a path to the Perl binary. It allows invoking the Perl scripts directly, without passing the file to the Perl as an argument. A Hashbang line in Perl looks like: #!/usr/bin/perl A Hashbang line is called so because it starts with a Hash(#) and a bang(!). A hashbang line in Perl holds significant importance in a Perl code. Now, let’s get started with the use of this Hashbang line. Example: Suppose we have a hello world program script of Perl which we will execute on a Linux system with the terminal. use strict;use warnings; print "Hello World\n"; Now, we will save it with the name hello.pl and in the terminal, we will execute it by – $ perl hello.pl Output:Here, in the above code, the terminal is running the Perl first and then the Perl is asked to run the code script. If the code script is run without invoking the Perl first then an error arises.Try running the code as shown below: $ hello.pl Output:Here, the shell we used, tried to interpret the commands in the file. However, it could not find the command print in Linux/Unix. Hence, there is a need to inform shell that it is a Perl script. This is the point where the concept of Hashbang comes into action. Hashbang informs the terminal about the script.However, before executing this code, there is a need to set the path of the shell to add the current directory to existing directories. This can be done by executing the following command: $ PATH = $PATH:$(pwd) This will append the current working directory to the list of directories in the PATH environment variable.Next, there is a need to add the Hash-bang line #!/usr/bin/perl in the Perl script file hello.pl. This line is always added at the beginning of the code i.e. the first line of the code script is the Hashbang line. #!/usr/bin/perluse strict;use warnings; print "Hello World\n"; If the above code is run as $ hello.pl, without executing the Perl first, then the output will be:Above code works fine and no error is produced because of the Hashbang line #!/usr/bin/perl added as the first line of the script. When the script is executed it is run in the current shell environment. If the script starts with a hash and a bang (hash-bang) #! then the shell will run execute the application that has its path on the hash-bang line (in this case /usr/bin/perl) which is the standard location of the Perl compiler-interpreter. So, the hash-bang line holds the path to the Perl compiler-interpreter.Now, the error occurs when there is no hash-bang line in the file and we try to execute it without running Perl explicitly. The shell assumes that the script is written in Bash and thus tries to execute it accordingly leading to errors. perl-basics Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | Writing to a File Perl Tutorial - Learn Perl With Examples Perl | Multidimensional Hashes Perl | File Handling Introduction Perl | Reading Excel Files Perl | Special Character Classes in Regular Expressions Perl | shift() Function Perl | Date and Time Perl | index() Function Perl | Appending to a File
[ { "code": null, "e": 23990, "s": 23962, "text": "\n11 Jul, 2019" }, { "code": null, "e": 24414, "s": 23990, "text": "Practical Extraction and Reporting Language or Perl is an interpreter based language. Hash-bangs or shebangs are useful when we are executing Perl scripts on Unix-like systems such as Linux and Mac OSX. A Hashbang line is the first line of a Perl program and is a path to the Perl binary. It allows invoking the Perl scripts directly, without passing the file to the Perl as an argument. A Hashbang line in Perl looks like:" }, { "code": null, "e": 24430, "s": 24414, "text": "#!/usr/bin/perl" }, { "code": null, "e": 24635, "s": 24430, "text": "A Hashbang line is called so because it starts with a Hash(#) and a bang(!). A hashbang line in Perl holds significant importance in a Perl code. Now, let’s get started with the use of this Hashbang line." }, { "code": null, "e": 24756, "s": 24635, "text": "Example: Suppose we have a hello world program script of Perl which we will execute on a Linux system with the terminal." }, { "code": "use strict;use warnings; print \"Hello World\\n\";", "e": 24806, "s": 24756, "text": null }, { "code": null, "e": 24895, "s": 24806, "text": "Now, we will save it with the name hello.pl and in the terminal, we will execute it by –" }, { "code": null, "e": 24912, "s": 24895, "text": "$ perl hello.pl\n" }, { "code": null, "e": 25150, "s": 24912, "text": "Output:Here, in the above code, the terminal is running the Perl first and then the Perl is asked to run the code script. If the code script is run without invoking the Perl first then an error arises.Try running the code as shown below:" }, { "code": null, "e": 25162, "s": 25150, "text": "$ hello.pl\n" }, { "code": null, "e": 25667, "s": 25162, "text": "Output:Here, the shell we used, tried to interpret the commands in the file. However, it could not find the command print in Linux/Unix. Hence, there is a need to inform shell that it is a Perl script. This is the point where the concept of Hashbang comes into action. Hashbang informs the terminal about the script.However, before executing this code, there is a need to set the path of the shell to add the current directory to existing directories. This can be done by executing the following command:" }, { "code": null, "e": 25690, "s": 25667, "text": "$ PATH = $PATH:$(pwd)\n" }, { "code": null, "e": 26011, "s": 25690, "text": "This will append the current working directory to the list of directories in the PATH environment variable.Next, there is a need to add the Hash-bang line #!/usr/bin/perl in the Perl script file hello.pl. This line is always added at the beginning of the code i.e. the first line of the code script is the Hashbang line." }, { "code": "#!/usr/bin/perluse strict;use warnings; print \"Hello World\\n\";", "e": 26076, "s": 26011, "text": null }, { "code": null, "e": 26305, "s": 26076, "text": "If the above code is run as $ hello.pl, without executing the Perl first, then the output will be:Above code works fine and no error is produced because of the Hashbang line #!/usr/bin/perl added as the first line of the script." }, { "code": null, "e": 26926, "s": 26305, "text": "When the script is executed it is run in the current shell environment. If the script starts with a hash and a bang (hash-bang) #! then the shell will run execute the application that has its path on the hash-bang line (in this case /usr/bin/perl) which is the standard location of the Perl compiler-interpreter. So, the hash-bang line holds the path to the Perl compiler-interpreter.Now, the error occurs when there is no hash-bang line in the file and we try to execute it without running Perl explicitly. The shell assumes that the script is written in Bash and thus tries to execute it accordingly leading to errors." }, { "code": null, "e": 26938, "s": 26926, "text": "perl-basics" }, { "code": null, "e": 26945, "s": 26938, "text": "Picked" }, { "code": null, "e": 26950, "s": 26945, "text": "Perl" }, { "code": null, "e": 26955, "s": 26950, "text": "Perl" }, { "code": null, "e": 27053, "s": 26955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27062, "s": 27053, "text": "Comments" }, { "code": null, "e": 27075, "s": 27062, "text": "Old Comments" }, { "code": null, "e": 27100, "s": 27075, "text": "Perl | Writing to a File" }, { "code": null, "e": 27141, "s": 27100, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 27172, "s": 27141, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 27206, "s": 27172, "text": "Perl | File Handling Introduction" }, { "code": null, "e": 27233, "s": 27206, "text": "Perl | Reading Excel Files" }, { "code": null, "e": 27289, "s": 27233, "text": "Perl | Special Character Classes in Regular Expressions" }, { "code": null, "e": 27313, "s": 27289, "text": "Perl | shift() Function" }, { "code": null, "e": 27334, "s": 27313, "text": "Perl | Date and Time" }, { "code": null, "e": 27358, "s": 27334, "text": "Perl | index() Function" } ]
CONCAT() function in SQL Server
28 Dec, 2020 CONCAT() :This function in SQL Server helps to concatenate two or more strings together. CONCAT() function can accept a minimum of 2 parameters and a maximum of 254 parameters. Syntax : CONCAT(string_1, string_2, .......string_n) Parameters : string_1, string_2, .......string_n –The given strings which need to be concatenated. Returns :The function concatenates all the given string and returns them as one whole string. Applicable to the following versions : SQL Server 2017 SQL Server 2016 SQL Server 2014 SQL Server 2012 Example-1 :The general working of CONCAT() function. Concatenating 3 strings together with space in between –SELECT CONCAT('PYTHON', ' ', 'is', ' ', 'fun!!!') As Combined;Output :CombinedPYTHON is fun!!! SELECT CONCAT('PYTHON', ' ', 'is', ' ', 'fun!!!') As Combined; Output : Concatenating more than 3 strings together –SELECT CONCAT ('Every', 'next', 'level', 'of', 'your', 'life', 'demands', 'a', 'new', 'you!') As Combined;Output :CombinedEverynextlevelofyourlifedemandsanewyou! SELECT CONCAT ('Every', 'next', 'level', 'of', 'your', 'life', 'demands', 'a', 'new', 'you!') As Combined; Output : Example-2 :Using a variable with CONCAT() function, we assign the strings to variables and then concatenate them. DECLARE @Str1 AS VARCHAR(100)='Think' DECLARE @Str2 AS VARCHAR(100)='-' DECLARE @Str3 AS VARCHAR(100)='green' DECLARE @Str4 AS VARCHAR(100)=' ' DECLARE @Str5 AS VARCHAR(100)='Be' DECLARE @Str6 AS VARCHAR(100)='-' DECLARE @Str7 AS VARCHAR(100)='green' SELECT CONCAT(@Str1, @Str2, @Str3, @str4, @str5, @str6, @str7) AS Combined; Output : Example-3 :Concatenating numerical expression using CONCAT() function, here in place of string we combined numeric values. SELECT CONCAT(13, 03, 1999) AS Combined; Output : DBMS-SQL SQL-Server Technical Scripter 2020 SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Dec, 2020" }, { "code": null, "e": 205, "s": 28, "text": "CONCAT() :This function in SQL Server helps to concatenate two or more strings together. CONCAT() function can accept a minimum of 2 parameters and a maximum of 254 parameters." }, { "code": null, "e": 214, "s": 205, "text": "Syntax :" }, { "code": null, "e": 258, "s": 214, "text": "CONCAT(string_1, string_2, .......string_n)" }, { "code": null, "e": 271, "s": 258, "text": "Parameters :" }, { "code": null, "e": 357, "s": 271, "text": "string_1, string_2, .......string_n –The given strings which need to be concatenated." }, { "code": null, "e": 451, "s": 357, "text": "Returns :The function concatenates all the given string and returns them as one whole string." }, { "code": null, "e": 490, "s": 451, "text": "Applicable to the following versions :" }, { "code": null, "e": 506, "s": 490, "text": "SQL Server 2017" }, { "code": null, "e": 522, "s": 506, "text": "SQL Server 2016" }, { "code": null, "e": 538, "s": 522, "text": "SQL Server 2014" }, { "code": null, "e": 554, "s": 538, "text": "SQL Server 2012" }, { "code": null, "e": 607, "s": 554, "text": "Example-1 :The general working of CONCAT() function." }, { "code": null, "e": 759, "s": 607, "text": "Concatenating 3 strings together with space in between –SELECT CONCAT('PYTHON', ' ', 'is', ' ', 'fun!!!') \nAs Combined;Output :CombinedPYTHON is fun!!!" }, { "code": null, "e": 823, "s": 759, "text": "SELECT CONCAT('PYTHON', ' ', 'is', ' ', 'fun!!!') \nAs Combined;" }, { "code": null, "e": 832, "s": 823, "text": "Output :" }, { "code": null, "e": 1039, "s": 832, "text": "Concatenating more than 3 strings together –SELECT CONCAT\n('Every', 'next', 'level', 'of', 'your', 'life', 'demands', 'a', 'new', 'you!') \nAs Combined;Output :CombinedEverynextlevelofyourlifedemandsanewyou!" }, { "code": null, "e": 1147, "s": 1039, "text": "SELECT CONCAT\n('Every', 'next', 'level', 'of', 'your', 'life', 'demands', 'a', 'new', 'you!') \nAs Combined;" }, { "code": null, "e": 1156, "s": 1147, "text": "Output :" }, { "code": null, "e": 1270, "s": 1156, "text": "Example-2 :Using a variable with CONCAT() function, we assign the strings to variables and then concatenate them." }, { "code": null, "e": 1598, "s": 1270, "text": "DECLARE @Str1 AS VARCHAR(100)='Think'\nDECLARE @Str2 AS VARCHAR(100)='-'\nDECLARE @Str3 AS VARCHAR(100)='green'\nDECLARE @Str4 AS VARCHAR(100)=' '\nDECLARE @Str5 AS VARCHAR(100)='Be'\nDECLARE @Str6 AS VARCHAR(100)='-'\nDECLARE @Str7 AS VARCHAR(100)='green'\n\nSELECT CONCAT(@Str1, @Str2, @Str3, @str4, @str5, @str6, @str7) AS Combined;" }, { "code": null, "e": 1607, "s": 1598, "text": "Output :" }, { "code": null, "e": 1730, "s": 1607, "text": "Example-3 :Concatenating numerical expression using CONCAT() function, here in place of string we combined numeric values." }, { "code": null, "e": 1772, "s": 1730, "text": "SELECT CONCAT(13, 03, 1999) \nAS Combined;" }, { "code": null, "e": 1781, "s": 1772, "text": "Output :" }, { "code": null, "e": 1790, "s": 1781, "text": "DBMS-SQL" }, { "code": null, "e": 1801, "s": 1790, "text": "SQL-Server" }, { "code": null, "e": 1825, "s": 1801, "text": "Technical Scripter 2020" }, { "code": null, "e": 1829, "s": 1825, "text": "SQL" }, { "code": null, "e": 1833, "s": 1829, "text": "SQL" } ]
Simple registration form using Python Tkinter
09 Sep, 2021 Prerequisites: Tkinter Introduction, openpyxl module.Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let’s make a simple information form GUI application using Tkinter. In this application, User has to fill up the required information, and that information is automatically written into an excel file. Firstly, create an empty excel file, after that pass an absolute path of the excel file in the program so that the program is able to access that excel file. Below is the implementation : Python3 # import openpyxl and tkinter modulesfrom openpyxl import *from tkinter import * # globally declare wb and sheet variable # opening the existing excel filewb = load_workbook('C:\\Users\\Admin\\Desktop\\excel.xlsx') # create the sheet objectsheet = wb.active def excel(): # resize the width of columns in # excel spreadsheet sheet.column_dimensions['A'].width = 30 sheet.column_dimensions['B'].width = 10 sheet.column_dimensions['C'].width = 10 sheet.column_dimensions['D'].width = 20 sheet.column_dimensions['E'].width = 20 sheet.column_dimensions['F'].width = 40 sheet.column_dimensions['G'].width = 50 # write given data to an excel spreadsheet # at particular location sheet.cell(row=1, column=1).value = "Name" sheet.cell(row=1, column=2).value = "Course" sheet.cell(row=1, column=3).value = "Semester" sheet.cell(row=1, column=4).value = "Form Number" sheet.cell(row=1, column=5).value = "Contact Number" sheet.cell(row=1, column=6).value = "Email id" sheet.cell(row=1, column=7).value = "Address" # Function to set focus (cursor)def focus1(event): # set focus on the course_field box course_field.focus_set() # Function to set focusdef focus2(event): # set focus on the sem_field box sem_field.focus_set() # Function to set focusdef focus3(event): # set focus on the form_no_field box form_no_field.focus_set() # Function to set focusdef focus4(event): # set focus on the contact_no_field box contact_no_field.focus_set() # Function to set focusdef focus5(event): # set focus on the email_id_field box email_id_field.focus_set() # Function to set focusdef focus6(event): # set focus on the address_field box address_field.focus_set() # Function for clearing the# contents of text entry boxesdef clear(): # clear the content of text entry box name_field.delete(0, END) course_field.delete(0, END) sem_field.delete(0, END) form_no_field.delete(0, END) contact_no_field.delete(0, END) email_id_field.delete(0, END) address_field.delete(0, END) # Function to take data from GUI# window and write to an excel filedef insert(): # if user not fill any entry # then print "empty input" if (name_field.get() == "" and course_field.get() == "" and sem_field.get() == "" and form_no_field.get() == "" and contact_no_field.get() == "" and email_id_field.get() == "" and address_field.get() == ""): print("empty input") else: # assigning the max row and max column # value upto which data is written # in an excel sheet to the variable current_row = sheet.max_row current_column = sheet.max_column # get method returns current text # as string which we write into # excel spreadsheet at particular location sheet.cell(row=current_row + 1, column=1).value = name_field.get() sheet.cell(row=current_row + 1, column=2).value = course_field.get() sheet.cell(row=current_row + 1, column=3).value = sem_field.get() sheet.cell(row=current_row + 1, column=4).value = form_no_field.get() sheet.cell(row=current_row + 1, column=5).value = contact_no_field.get() sheet.cell(row=current_row + 1, column=6).value = email_id_field.get() sheet.cell(row=current_row + 1, column=7).value = address_field.get() # save the file wb.save('C:\\Users\\Admin\\Desktop\\excel.xlsx') # set focus on the name_field box name_field.focus_set() # call the clear() function clear() # Driver codeif __name__ == "__main__": # create a GUI window root = Tk() # set the background colour of GUI window root.configure(background='light green') # set the title of GUI window root.title("registration form") # set the configuration of GUI window root.geometry("500x300") excel() # create a Form label heading = Label(root, text="Form", bg="light green") # create a Name label name = Label(root, text="Name", bg="light green") # create a Course label course = Label(root, text="Course", bg="light green") # create a Semester label sem = Label(root, text="Semester", bg="light green") # create a Form No. label form_no = Label(root, text="Form No.", bg="light green") # create a Contact No. label contact_no = Label(root, text="Contact No.", bg="light green") # create a Email id label email_id = Label(root, text="Email id", bg="light green") # create a address label address = Label(root, text="Address", bg="light green") # grid method is used for placing # the widgets at respective positions # in table like structure . heading.grid(row=0, column=1) name.grid(row=1, column=0) course.grid(row=2, column=0) sem.grid(row=3, column=0) form_no.grid(row=4, column=0) contact_no.grid(row=5, column=0) email_id.grid(row=6, column=0) address.grid(row=7, column=0) # create a text entry box # for typing the information name_field = Entry(root) course_field = Entry(root) sem_field = Entry(root) form_no_field = Entry(root) contact_no_field = Entry(root) email_id_field = Entry(root) address_field = Entry(root) # bind method of widget is used for # the binding the function with the events # whenever the enter key is pressed # then call the focus1 function name_field.bind("<Return>", focus1) # whenever the enter key is pressed # then call the focus2 function course_field.bind("<Return>", focus2) # whenever the enter key is pressed # then call the focus3 function sem_field.bind("<Return>", focus3) # whenever the enter key is pressed # then call the focus4 function form_no_field.bind("<Return>", focus4) # whenever the enter key is pressed # then call the focus5 function contact_no_field.bind("<Return>", focus5) # whenever the enter key is pressed # then call the focus6 function email_id_field.bind("<Return>", focus6) # grid method is used for placing # the widgets at respective positions # in table like structure . name_field.grid(row=1, column=1, ipadx="100") course_field.grid(row=2, column=1, ipadx="100") sem_field.grid(row=3, column=1, ipadx="100") form_no_field.grid(row=4, column=1, ipadx="100") contact_no_field.grid(row=5, column=1, ipadx="100") email_id_field.grid(row=6, column=1, ipadx="100") address_field.grid(row=7, column=1, ipadx="100") # call excel function excel() # create a Submit Button and place into the root window submit = Button(root, text="Submit", fg="Black", bg="Red", command=insert) submit.grid(row=8, column=1) # start the GUI root.mainloop() Output : Registration Form Using Python Tkinter | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersRegistration Form Using Python Tkinter | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 36:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=c3rp-iKe3cI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Akanksha_Rai simranarora5sos Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Sep, 2021" }, { "code": null, "e": 479, "s": 54, "text": "Prerequisites: Tkinter Introduction, openpyxl module.Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let’s make a simple information form GUI application using Tkinter. In this application, User has to fill up the required information, and that information is automatically written into an excel file." }, { "code": null, "e": 637, "s": 479, "text": "Firstly, create an empty excel file, after that pass an absolute path of the excel file in the program so that the program is able to access that excel file." }, { "code": null, "e": 668, "s": 637, "text": "Below is the implementation : " }, { "code": null, "e": 676, "s": 668, "text": "Python3" }, { "code": "# import openpyxl and tkinter modulesfrom openpyxl import *from tkinter import * # globally declare wb and sheet variable # opening the existing excel filewb = load_workbook('C:\\\\Users\\\\Admin\\\\Desktop\\\\excel.xlsx') # create the sheet objectsheet = wb.active def excel(): # resize the width of columns in # excel spreadsheet sheet.column_dimensions['A'].width = 30 sheet.column_dimensions['B'].width = 10 sheet.column_dimensions['C'].width = 10 sheet.column_dimensions['D'].width = 20 sheet.column_dimensions['E'].width = 20 sheet.column_dimensions['F'].width = 40 sheet.column_dimensions['G'].width = 50 # write given data to an excel spreadsheet # at particular location sheet.cell(row=1, column=1).value = \"Name\" sheet.cell(row=1, column=2).value = \"Course\" sheet.cell(row=1, column=3).value = \"Semester\" sheet.cell(row=1, column=4).value = \"Form Number\" sheet.cell(row=1, column=5).value = \"Contact Number\" sheet.cell(row=1, column=6).value = \"Email id\" sheet.cell(row=1, column=7).value = \"Address\" # Function to set focus (cursor)def focus1(event): # set focus on the course_field box course_field.focus_set() # Function to set focusdef focus2(event): # set focus on the sem_field box sem_field.focus_set() # Function to set focusdef focus3(event): # set focus on the form_no_field box form_no_field.focus_set() # Function to set focusdef focus4(event): # set focus on the contact_no_field box contact_no_field.focus_set() # Function to set focusdef focus5(event): # set focus on the email_id_field box email_id_field.focus_set() # Function to set focusdef focus6(event): # set focus on the address_field box address_field.focus_set() # Function for clearing the# contents of text entry boxesdef clear(): # clear the content of text entry box name_field.delete(0, END) course_field.delete(0, END) sem_field.delete(0, END) form_no_field.delete(0, END) contact_no_field.delete(0, END) email_id_field.delete(0, END) address_field.delete(0, END) # Function to take data from GUI# window and write to an excel filedef insert(): # if user not fill any entry # then print \"empty input\" if (name_field.get() == \"\" and course_field.get() == \"\" and sem_field.get() == \"\" and form_no_field.get() == \"\" and contact_no_field.get() == \"\" and email_id_field.get() == \"\" and address_field.get() == \"\"): print(\"empty input\") else: # assigning the max row and max column # value upto which data is written # in an excel sheet to the variable current_row = sheet.max_row current_column = sheet.max_column # get method returns current text # as string which we write into # excel spreadsheet at particular location sheet.cell(row=current_row + 1, column=1).value = name_field.get() sheet.cell(row=current_row + 1, column=2).value = course_field.get() sheet.cell(row=current_row + 1, column=3).value = sem_field.get() sheet.cell(row=current_row + 1, column=4).value = form_no_field.get() sheet.cell(row=current_row + 1, column=5).value = contact_no_field.get() sheet.cell(row=current_row + 1, column=6).value = email_id_field.get() sheet.cell(row=current_row + 1, column=7).value = address_field.get() # save the file wb.save('C:\\\\Users\\\\Admin\\\\Desktop\\\\excel.xlsx') # set focus on the name_field box name_field.focus_set() # call the clear() function clear() # Driver codeif __name__ == \"__main__\": # create a GUI window root = Tk() # set the background colour of GUI window root.configure(background='light green') # set the title of GUI window root.title(\"registration form\") # set the configuration of GUI window root.geometry(\"500x300\") excel() # create a Form label heading = Label(root, text=\"Form\", bg=\"light green\") # create a Name label name = Label(root, text=\"Name\", bg=\"light green\") # create a Course label course = Label(root, text=\"Course\", bg=\"light green\") # create a Semester label sem = Label(root, text=\"Semester\", bg=\"light green\") # create a Form No. label form_no = Label(root, text=\"Form No.\", bg=\"light green\") # create a Contact No. label contact_no = Label(root, text=\"Contact No.\", bg=\"light green\") # create a Email id label email_id = Label(root, text=\"Email id\", bg=\"light green\") # create a address label address = Label(root, text=\"Address\", bg=\"light green\") # grid method is used for placing # the widgets at respective positions # in table like structure . heading.grid(row=0, column=1) name.grid(row=1, column=0) course.grid(row=2, column=0) sem.grid(row=3, column=0) form_no.grid(row=4, column=0) contact_no.grid(row=5, column=0) email_id.grid(row=6, column=0) address.grid(row=7, column=0) # create a text entry box # for typing the information name_field = Entry(root) course_field = Entry(root) sem_field = Entry(root) form_no_field = Entry(root) contact_no_field = Entry(root) email_id_field = Entry(root) address_field = Entry(root) # bind method of widget is used for # the binding the function with the events # whenever the enter key is pressed # then call the focus1 function name_field.bind(\"<Return>\", focus1) # whenever the enter key is pressed # then call the focus2 function course_field.bind(\"<Return>\", focus2) # whenever the enter key is pressed # then call the focus3 function sem_field.bind(\"<Return>\", focus3) # whenever the enter key is pressed # then call the focus4 function form_no_field.bind(\"<Return>\", focus4) # whenever the enter key is pressed # then call the focus5 function contact_no_field.bind(\"<Return>\", focus5) # whenever the enter key is pressed # then call the focus6 function email_id_field.bind(\"<Return>\", focus6) # grid method is used for placing # the widgets at respective positions # in table like structure . name_field.grid(row=1, column=1, ipadx=\"100\") course_field.grid(row=2, column=1, ipadx=\"100\") sem_field.grid(row=3, column=1, ipadx=\"100\") form_no_field.grid(row=4, column=1, ipadx=\"100\") contact_no_field.grid(row=5, column=1, ipadx=\"100\") email_id_field.grid(row=6, column=1, ipadx=\"100\") address_field.grid(row=7, column=1, ipadx=\"100\") # call excel function excel() # create a Submit Button and place into the root window submit = Button(root, text=\"Submit\", fg=\"Black\", bg=\"Red\", command=insert) submit.grid(row=8, column=1) # start the GUI root.mainloop()", "e": 7485, "s": 676, "text": null }, { "code": null, "e": 7496, "s": 7485, "text": "Output : " }, { "code": null, "e": 8393, "s": 7498, "text": "Registration Form Using Python Tkinter | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersRegistration Form Using Python Tkinter | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 36:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=c3rp-iKe3cI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 8408, "s": 8395, "text": "Akanksha_Rai" }, { "code": null, "e": 8424, "s": 8408, "text": "simranarora5sos" }, { "code": null, "e": 8432, "s": 8424, "text": "Project" }, { "code": null, "e": 8439, "s": 8432, "text": "Python" } ]
Linear Regression Implementation From Scratch using Python
01 Oct, 2020 Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for prediction is represented by h( x ). h( x ) = w * x + b here, b is the bias. x represents the feature vector w represents the weight vector. Linear regression with one variable is also called univariant linear regression. After initializing the weight vector, we can find the weight vector to best fit the model by ordinary least squares method or gradient descent learning. Mathematical Intuition: The cost function (or loss function) is used to measure the performance of a machine learning model or quantifies the error between the expected values and the values predicted by our hypothetical function. The cost function for Linear Regression is represented by J. Here, m is the total number of training examples in the dataset. y(i) represents the value of target variable for ith training example. So, our objective is to minimize the cost function J (or improve the performance of our machine learning model). To do this, we have to find the weights at which J is minimum. One such algorithm which can be used to minimize any differentiable function is Gradient Descent. It is a first-order iterative optimizing algorithm that takes us to a minimum of a function. Pseudo Code: Start with some wKeep changing w to reduce J( w ) until we hopefully end up at a minimum. Start with some w Keep changing w to reduce J( w ) until we hopefully end up at a minimum. Algorithm: repeat until convergence { tmpi = wi - alpha * dwi wi = tmpi } where alpha is the learning rate. Dataset used in this implementation can be downloaded from link. It has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will train a Linear Regression model to learn the correlation between the number of years of experience of each employee and their respective salary. Once the model is trained, we will be able to predict the salary of an employee on the basis of his years of experience. Python3 # Importing libraries import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Linear Regression class LinearRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : Y_pred = self.predict( self.X ) # calculate gradients dW = - ( 2 * ( self.X.T ).dot( self.Y - Y_pred ) ) / self.m db = - 2 * np.sum( self.Y - Y_pred ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : return X.dot( self.W ) + self.b # driver code def main() : # Importing dataset df = pd.read_csv( "salary_data.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = LinearRegression( iterations = 1000, learning_rate = 0.01 ) model.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) print( "Predicted values ", np.round( Y_pred[:3], 2 ) ) print( "Real values ", Y_test[:3] ) print( "Trained W ", round( model.W[0], 2 ) ) print( "Trained b ", round( model.b, 2 ) ) # Visualization on test set plt.scatter( X_test, Y_test, color = 'blue' ) plt.plot( X_test, Y_pred, color = 'orange' ) plt.title( 'Salary vs Experience' ) plt.xlabel( 'Years of Experience' ) plt.ylabel( 'Salary' ) plt.show() if __name__ == "__main__" : main() Predicted values [ 40594.69 123305.18 65031.88] Real values [ 37731 122391 57081] Trained W 9398.92 Trained b 26496.31 Linear Regression Visualization Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Oct, 2020" }, { "code": null, "e": 435, "s": 54, "text": "Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for prediction is represented by h( x )." }, { "code": null, "e": 555, "s": 435, "text": " h( x ) = w * x + b \n \n here, b is the bias.\n x represents the feature vector\n w represents the weight vector.\n" }, { "code": null, "e": 790, "s": 555, "text": "Linear regression with one variable is also called univariant linear regression. After initializing the weight vector, we can find the weight vector to best fit the model by ordinary least squares method or gradient descent learning." }, { "code": null, "e": 1082, "s": 790, "text": "Mathematical Intuition: The cost function (or loss function) is used to measure the performance of a machine learning model or quantifies the error between the expected values and the values predicted by our hypothetical function. The cost function for Linear Regression is represented by J." }, { "code": null, "e": 1221, "s": 1084, "text": "Here, m is the total number of training examples in the dataset.\ny(i) represents the value of target variable for ith training example.\n" }, { "code": null, "e": 1589, "s": 1221, "text": "So, our objective is to minimize the cost function J (or improve the performance of our machine learning model). To do this, we have to find the weights at which J is minimum. One such algorithm which can be used to minimize any differentiable function is Gradient Descent. It is a first-order iterative optimizing algorithm that takes us to a minimum of a function." }, { "code": null, "e": 1602, "s": 1589, "text": "Pseudo Code:" }, { "code": null, "e": 1692, "s": 1602, "text": "Start with some wKeep changing w to reduce J( w ) until we hopefully end up at a minimum." }, { "code": null, "e": 1710, "s": 1692, "text": "Start with some w" }, { "code": null, "e": 1783, "s": 1710, "text": "Keep changing w to reduce J( w ) until we hopefully end up at a minimum." }, { "code": null, "e": 1795, "s": 1783, "text": "Algorithm: " }, { "code": null, "e": 1932, "s": 1795, "text": "repeat until convergence {\n tmpi = wi - alpha * dwi \n wi = tmpi \n}\nwhere alpha is the learning rate.\n" }, { "code": null, "e": 1997, "s": 1932, "text": "Dataset used in this implementation can be downloaded from link." }, { "code": null, "e": 2364, "s": 1997, "text": "It has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will train a Linear Regression model to learn the correlation between the number of years of experience of each employee and their respective salary. Once the model is trained, we will be able to predict the salary of an employee on the basis of his years of experience." }, { "code": null, "e": 2372, "s": 2364, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Linear Regression class LinearRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : Y_pred = self.predict( self.X ) # calculate gradients dW = - ( 2 * ( self.X.T ).dot( self.Y - Y_pred ) ) / self.m db = - 2 * np.sum( self.Y - Y_pred ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : return X.dot( self.W ) + self.b # driver code def main() : # Importing dataset df = pd.read_csv( \"salary_data.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = LinearRegression( iterations = 1000, learning_rate = 0.01 ) model.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) print( \"Predicted values \", np.round( Y_pred[:3], 2 ) ) print( \"Real values \", Y_test[:3] ) print( \"Trained W \", round( model.W[0], 2 ) ) print( \"Trained b \", round( model.b, 2 ) ) # Visualization on test set plt.scatter( X_test, Y_test, color = 'blue' ) plt.plot( X_test, Y_pred, color = 'orange' ) plt.title( 'Salary vs Experience' ) plt.xlabel( 'Years of Experience' ) plt.ylabel( 'Salary' ) plt.show() if __name__ == \"__main__\" : main()", "e": 5018, "s": 2372, "text": null }, { "code": null, "e": 5163, "s": 5018, "text": "Predicted values [ 40594.69 123305.18 65031.88]\nReal values [ 37731 122391 57081]\nTrained W 9398.92\nTrained b 26496.31\n" }, { "code": null, "e": 5195, "s": 5163, "text": "Linear Regression Visualization" }, { "code": null, "e": 5212, "s": 5195, "text": "Machine Learning" }, { "code": null, "e": 5219, "s": 5212, "text": "Python" }, { "code": null, "e": 5236, "s": 5219, "text": "Machine Learning" } ]
Salesforce Interview Experience for SDE Internship (On-Campus)
08 Sep, 2020 This article is about my Internship Interview experience with Salesforce’s Campus Recruitment Program (Futureforce) at IIT (ISM) Dhanbad. The process took place in the first week of September in total virtual mode. Round 1:Online Coding Round Platform: Hackerrank Duration: 1 hour 15 min. No. Of Questions: 3 Questions are as follows: Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations.Example:Input:"abc" Output:3 Eplaination:"cab", "bca", "abc". Input:"aaa" Output:1 Eplaination:"aaa". This was a pretty easy question and the expected time complexity for this was O(n).Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order.Input:"Entrance Vault 75" "Entrance CorridorA 55" "CorridorA Vault 15" Output:"Entrance CorridorA Vault 70" "Entrance Vault 75" Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations.Example:Input:"abc" Output:3 Eplaination:"cab", "bca", "abc". Input:"aaa" Output:1 Eplaination:"aaa". Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations. Example: Input:"abc" Output:3 Eplaination:"cab", "bca", "abc". Input:"aaa" Output:1 Eplaination:"aaa". This was a pretty easy question and the expected time complexity for this was O(n). Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order.Input:"Entrance Vault 75" "Entrance CorridorA 55" "CorridorA Vault 15" Output:"Entrance CorridorA Vault 70" "Entrance Vault 75" Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order. Input:"Entrance Vault 75" "Entrance CorridorA 55" "CorridorA Vault 15" Output:"Entrance CorridorA Vault 70" "Entrance Vault 75" This question seems to be simple and similar to find all sources to destination paths but the main problem was that all the inputs were in a string form and one must have to build suitable input by parsing through it. Many students got stuck here in parsing and debugging their code. Given only n number of characters can be printed in a line. Left aligns a given text using suitable padding. It was a fairly easy question of implementation and test cases were quite easy too with no hard edge cases. More than 200 students participated in this round and those who completed at least 2.5 questions were shortlisted for the next round. I did all three questions, so I got shortlisted with 13 other students for the interviews. Round 2: First Technical Interview on Google Meet. For this round, I have been provided a hackerrank codepair link to code online. The interviewer began with a healthy introduction of him and then to light down the atmosphere, he asked me about my lockdown experience and all. After a conversation of about 5-6 min, he jumped to my cv and asked me to introduce one of my projects. Out of my expectation, he further asked me to draw the whole system flow of the project on the whiteboard provided on codepair. I did the same as per his query and after about a discussion of about 10-15 min. he moved to problem-solving. He asked me to implement the LRU cache algorithm on the codepair. I wrote the complete code which can be found here and it got compiled and run in the first attempt. After this question, he asked me one more question based on linked list implementation and then moved to the oops concepts. He asked me questions like what is the difference between abstract class and interface, what is an inner class and how it is different from an inheritance, what is polymorphism and how can we achieve run time polymorphism, etc. I started answering by giving definitions but soon he stopped me and asked me to provide real-life examples for each one of them and then counter questioned me again and again. This discussion lasts around 20-25 min. After that, he asked me a puzzle based on the divide and conquer approach and asked me to write step by step iterations of its solution. This round took around 1 hour to complete. The interviewer was very polite and helpful. After this round, 5 students got eliminated and the rest moved to the second round of interviews. Round 3: Second Technical Interview on Google Meet. For this round again a codepair link was provided. The interviewer first asked me to introduce myself and interact with me for 2-3 min. After that, he started questioning me on problem-solving. The first question was, Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements.Example:Input:{4,5,3,2} Output:2 Explaination:{{4,3,2},{5,3,2}} Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements.Example:Input:{4,5,3,2} Output:2 Explaination:{{4,3,2},{5,3,2}} Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements. Example: Input:{4,5,3,2} Output:2 Explaination:{{4,3,2},{5,3,2}} I quickly wrote a brute force solution with time complexity of O(n3), but for some test cases it was showing TLE, so he asked me to optimize my solution. I thought for about 1 min. and then told him an approach with three-pointers and code it quickly. But as the array was not in the sorted form it did not work. Then he gave me a hint to use the merge sort concept and guide me to the approach slowly. Finally, I completed my solution, and he seemed to be satisfied with it. Then he moved to oops concepts and asked me to define copy constructor, static and dynamic binding, and type conversions. Then he moved to Operating Systems and asked me to illustrate concurrency problems and semaphores. Then he further asked me what are the operations allowed on semaphore and quickly define Producer-Consumer Problem. Then he moved to DBMS and asked me a couple of questions on Locking and DBA responsibilities. At this time me network had some issues so our meeting went off, and we began again from where we left in around 5-6 min. He was very supportive and understanding in this case. He asked me 2-3 questions on Computer Networks like ducking and Cryptography. He was certainly very satisfied with all the answers I gave him. In the end, he asked me if I had any question, so I asked me feedback on my interview, and he told me that most of the candidates give their most priorities on Problem Solving and DSA only and ignore other computer science concepts, but I answered him all the question on computer science that gave me an extra edge over other candidates. This round lasts about 55 min. and I was immediately informed that I have been moved to the last interview round. Round 4: Final Interview on Google Meet. As per my expectations, this round should have been an HR round and it was in the beginning as he asked me to explain to me the project, what challenges I faced during it and why I chose that project. But suddenly out of my expectation he moved to problem-solving and gave me a question. The problem was, given two sorted arrays A and B with some extra space in the B array. I have to merge them in O(n) time complexity without using additional space. I provide him 2-3 approaches for it and wrote the code for it too. Then he gave me a puzzle to find the minimum number of weighing operations to find one odd weight ball in a pool of 6 balls where the rest five are identical in weight. I provide him a satisfactory answer and in the end, he asked me if I have any questions for him. I asked a couple of questions about the company and its working culture. This round lasts about 25 min. and in the evening we received the results. 4 students were selected from my college and I was one of them The key things I learn through these interviews were, try to be practical and calm as much as you can, do not sit silently for too long, do not ignore computer science subjects, and practice problem solving as much as you can. All The Best !! Marketing On-Campus Salesforce Internship Interview Experiences Salesforce Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2020" }, { "code": null, "e": 244, "s": 28, "text": "This article is about my Internship Interview experience with Salesforce’s Campus Recruitment Program (Futureforce) at IIT (ISM) Dhanbad. The process took place in the first week of September in total virtual mode. " }, { "code": null, "e": 272, "s": 244, "text": "Round 1:Online Coding Round" }, { "code": null, "e": 293, "s": 272, "text": "Platform: Hackerrank" }, { "code": null, "e": 318, "s": 293, "text": "Duration: 1 hour 15 min." }, { "code": null, "e": 338, "s": 318, "text": "No. Of Questions: 3" }, { "code": null, "e": 364, "s": 338, "text": "Questions are as follows:" }, { "code": null, "e": 1301, "s": 364, "text": "Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations.Example:Input:\"abc\" Output:3 Eplaination:\"cab\", \"bca\", \"abc\".\nInput:\"aaa\" Output:1 Eplaination:\"aaa\".\nThis was a pretty easy question and the expected time complexity for this was O(n).Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order.Input:\"Entrance Vault 75\"\n \"Entrance CorridorA 55\"\n \"CorridorA Vault 15\"\nOutput:\"Entrance CorridorA Vault 70\"\n \"Entrance Vault 75\"\n" }, { "code": null, "e": 1527, "s": 1301, "text": "Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations.Example:Input:\"abc\" Output:3 Eplaination:\"cab\", \"bca\", \"abc\".\nInput:\"aaa\" Output:1 Eplaination:\"aaa\".\n" }, { "code": null, "e": 1647, "s": 1527, "text": "Given a string of length n. Right rotate it n times and count the total number of distinct strings after all rotations." }, { "code": null, "e": 1656, "s": 1647, "text": "Example:" }, { "code": null, "e": 1755, "s": 1656, "text": "Input:\"abc\" Output:3 Eplaination:\"cab\", \"bca\", \"abc\".\nInput:\"aaa\" Output:1 Eplaination:\"aaa\".\n" }, { "code": null, "e": 1839, "s": 1755, "text": "This was a pretty easy question and the expected time complexity for this was O(n)." }, { "code": null, "e": 2468, "s": 1839, "text": "Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order.Input:\"Entrance Vault 75\"\n \"Entrance CorridorA 55\"\n \"CorridorA Vault 15\"\nOutput:\"Entrance CorridorA Vault 70\"\n \"Entrance Vault 75\"\n" }, { "code": null, "e": 2950, "s": 2468, "text": "Given an entrance point and a vault and different corridors connecting them. Each connection has a cost to travel along with it. Generate all entrance to vault paths along with the total cost for that path. All resulting paths should be in non-decreasing order of their associated cost. If for two paths total cost is the same then the path with the fewer number of corridors visited should come first. If no. of corridors are also the same then they should be in alphabetic order." }, { "code": null, "e": 3098, "s": 2950, "text": "Input:\"Entrance Vault 75\"\n \"Entrance CorridorA 55\"\n \"CorridorA Vault 15\"\nOutput:\"Entrance CorridorA Vault 70\"\n \"Entrance Vault 75\"\n" }, { "code": null, "e": 3382, "s": 3098, "text": "This question seems to be simple and similar to find all sources to destination paths but the main problem was that all the inputs were in a string form and one must have to build suitable input by parsing through it. Many students got stuck here in parsing and debugging their code." }, { "code": null, "e": 3599, "s": 3382, "text": "Given only n number of characters can be printed in a line. Left aligns a given text using suitable padding. It was a fairly easy question of implementation and test cases were quite easy too with no hard edge cases." }, { "code": null, "e": 3824, "s": 3599, "text": "More than 200 students participated in this round and those who completed at least 2.5 questions were shortlisted for the next round. I did all three questions, so I got shortlisted with 13 other students for the interviews." }, { "code": null, "e": 5316, "s": 3824, "text": "Round 2: First Technical Interview on Google Meet. For this round, I have been provided a hackerrank codepair link to code online. The interviewer began with a healthy introduction of him and then to light down the atmosphere, he asked me about my lockdown experience and all. After a conversation of about 5-6 min, he jumped to my cv and asked me to introduce one of my projects. Out of my expectation, he further asked me to draw the whole system flow of the project on the whiteboard provided on codepair. I did the same as per his query and after about a discussion of about 10-15 min. he moved to problem-solving. He asked me to implement the LRU cache algorithm on the codepair. I wrote the complete code which can be found here and it got compiled and run in the first attempt. After this question, he asked me one more question based on linked list implementation and then moved to the oops concepts. He asked me questions like what is the difference between abstract class and interface, what is an inner class and how it is different from an inheritance, what is polymorphism and how can we achieve run time polymorphism, etc. I started answering by giving definitions but soon he stopped me and asked me to provide real-life examples for each one of them and then counter questioned me again and again. This discussion lasts around 20-25 min. After that, he asked me a puzzle based on the divide and conquer approach and asked me to write step by step iterations of its solution. " }, { "code": null, "e": 5502, "s": 5316, "text": "This round took around 1 hour to complete. The interviewer was very polite and helpful. After this round, 5 students got eliminated and the rest moved to the second round of interviews." }, { "code": null, "e": 5773, "s": 5502, "text": "Round 3: Second Technical Interview on Google Meet. For this round again a codepair link was provided. The interviewer first asked me to introduce myself and interact with me for 2-3 min. After that, he started questioning me on problem-solving. The first question was, " }, { "code": null, "e": 5963, "s": 5773, "text": "Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements.Example:Input:{4,5,3,2}\nOutput:2\nExplaination:{{4,3,2},{5,3,2}}" }, { "code": null, "e": 6153, "s": 5963, "text": "Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements.Example:Input:{4,5,3,2}\nOutput:2\nExplaination:{{4,3,2},{5,3,2}}" }, { "code": null, "e": 6280, "s": 6153, "text": "Given an array, count all inversions of length three where we can define an inversion to be a decreasing sequence of elements." }, { "code": null, "e": 6289, "s": 6280, "text": "Example:" }, { "code": null, "e": 6345, "s": 6289, "text": "Input:{4,5,3,2}\nOutput:2\nExplaination:{{4,3,2},{5,3,2}}" }, { "code": null, "e": 7911, "s": 6345, "text": "I quickly wrote a brute force solution with time complexity of O(n3), but for some test cases it was showing TLE, so he asked me to optimize my solution. I thought for about 1 min. and then told him an approach with three-pointers and code it quickly. But as the array was not in the sorted form it did not work. Then he gave me a hint to use the merge sort concept and guide me to the approach slowly. Finally, I completed my solution, and he seemed to be satisfied with it. Then he moved to oops concepts and asked me to define copy constructor, static and dynamic binding, and type conversions. Then he moved to Operating Systems and asked me to illustrate concurrency problems and semaphores. Then he further asked me what are the operations allowed on semaphore and quickly define Producer-Consumer Problem. Then he moved to DBMS and asked me a couple of questions on Locking and DBA responsibilities. At this time me network had some issues so our meeting went off, and we began again from where we left in around 5-6 min. He was very supportive and understanding in this case. He asked me 2-3 questions on Computer Networks like ducking and Cryptography. He was certainly very satisfied with all the answers I gave him. In the end, he asked me if I had any question, so I asked me feedback on my interview, and he told me that most of the candidates give their most priorities on Problem Solving and DSA only and ignore other computer science concepts, but I answered him all the question on computer science that gave me an extra edge over other candidates." }, { "code": null, "e": 8025, "s": 7911, "text": "This round lasts about 55 min. and I was immediately informed that I have been moved to the last interview round." }, { "code": null, "e": 8924, "s": 8025, "text": "Round 4: Final Interview on Google Meet. As per my expectations, this round should have been an HR round and it was in the beginning as he asked me to explain to me the project, what challenges I faced during it and why I chose that project. But suddenly out of my expectation he moved to problem-solving and gave me a question. The problem was, given two sorted arrays A and B with some extra space in the B array. I have to merge them in O(n) time complexity without using additional space. I provide him 2-3 approaches for it and wrote the code for it too. Then he gave me a puzzle to find the minimum number of weighing operations to find one odd weight ball in a pool of 6 balls where the rest five are identical in weight. I provide him a satisfactory answer and in the end, he asked me if I have any questions for him. I asked a couple of questions about the company and its working culture." }, { "code": null, "e": 9063, "s": 8924, "text": "This round lasts about 25 min. and in the evening we received the results. 4 students were selected from my college and I was one of them " }, { "code": null, "e": 9290, "s": 9063, "text": "The key things I learn through these interviews were, try to be practical and calm as much as you can, do not sit silently for too long, do not ignore computer science subjects, and practice problem solving as much as you can." }, { "code": null, "e": 9306, "s": 9290, "text": "All The Best !!" }, { "code": null, "e": 9316, "s": 9306, "text": "Marketing" }, { "code": null, "e": 9326, "s": 9316, "text": "On-Campus" }, { "code": null, "e": 9337, "s": 9326, "text": "Salesforce" }, { "code": null, "e": 9348, "s": 9337, "text": "Internship" }, { "code": null, "e": 9370, "s": 9348, "text": "Interview Experiences" }, { "code": null, "e": 9381, "s": 9370, "text": "Salesforce" } ]
How to fadeOut and remove a div using jQuery ?
03 Jun, 2019 Given a div element. The task is to remove it with a fadeOut effect using JQuery. Here are few methods discussed.First few methods to know. jQuery text() Method:This method sets/returns the text content of the selected elements.If this method is used to return content, it provides the text content of all matched elements (HTML tags will be removed).If this method is used to set content, it replace the content of ALL matched elements.Syntax:Returns text content:$(selector).text() Sets text content:$(selector).text(content) Set text content using a function:$(selector).text(function(index, curContent)) Parameters:content: This parameter is required. It specifies the new text content for the selected elements.function(index, curContent): This parameter is optional. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements. Returns text content:$(selector).text() $(selector).text() Sets text content:$(selector).text(content) $(selector).text(content) Set text content using a function:$(selector).text(function(index, curContent)) $(selector).text(function(index, curContent)) Parameters: content: This parameter is required. It specifies the new text content for the selected elements. function(index, curContent): This parameter is optional. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements. index: It returns the index position of the element in the set. curContent: It returns current content of selected elements. jQuery Effect fadeOut() MethodThis method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).Syntax:$(selector).fadeOut(speed, easing, callback) Parameters:speed: This parameter is optional. It specifies the speed of the fading effect. Default value = 400 milliseconds.Applicable values.milliseconds“slow”“fast”easing: This parameter is Optional. It specifies the speed of the element in different points of the animation. Default value = “swing”.Applicable values.“swing”: It starts slowly, but faster in the middle.“linear”: It moves in a constant speed.callback: This parameter is optional. It specifies a function to be executed after the fadeOut() method is completed. $(selector).fadeOut(speed, easing, callback) Parameters: speed: This parameter is optional. It specifies the speed of the fading effect. Default value = 400 milliseconds.Applicable values.milliseconds“slow”“fast” milliseconds “slow” “fast” easing: This parameter is Optional. It specifies the speed of the element in different points of the animation. Default value = “swing”.Applicable values.“swing”: It starts slowly, but faster in the middle.“linear”: It moves in a constant speed. “swing”: It starts slowly, but faster in the middle. “linear”: It moves in a constant speed. callback: This parameter is optional. It specifies a function to be executed after the fadeOut() method is completed. jQuery on() MethodThis method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map) Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. $(selector).on(event, childSelector, data, function, map) Parameters: event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In case of multiple event values, those are separated by space. Event must be a valid. childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements. data: This parameter is optional. It specifies additional data to pass to the function. function: This parameter is required. It specifies the function to run when the event occurs. map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. jQuery remove() MethodThis method removes the selected elements, including all text and child nodes along with the data and events of the selected elements.Syntax:$(selector).remove(selector) Parameters:event: This parameter is optional. It specifies one or more elements to be removed. Use comma as separator to remove multiple elements. $(selector).remove(selector) Parameters: event: This parameter is optional. It specifies one or more elements to be removed. Use comma as separator to remove multiple elements. Example 1: In this example the div element is removed after fadeOut effect for 300 milliseconds. <!DOCTYPE HTML><html> <head> <title> JQuery | How to FadeOut and Remove a div. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #div { height: 60px; width: 200px; background-color: green; margin: 0 auto; } </style></head> <body style="text-align:center;" id="body"> <h1 id="h" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> click the button to remove DIV with fade effect. </p> <div id="div"> </div> <br> <button> click to remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('button').on('click', function(e) { $('#div').fadeOut(300, function() { $('#div').remove(); }); $("#GFG_DOWN").text("DIV Removed"); }); </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example is similar to previous. In this example the div element is removed after fadeOut effect for 300 milliseconds with a different approach. <!DOCTYPE HTML><html> <head> <title> JQuery | How to FadeOut and Remove a div. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #div { height: 60px; width: 200px; background-color: green; margin: 0 auto; } </style></head> <body style="text-align:center;" id="body"> <h1 id="h" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> click the button to remove DIV with fade effect. </p> <div id="div"> </div> <br> <button onclick='$("#div").fadeOut(300, function() { $(this).remove(); $("#GFG_DOWN") .text("DIV Removed"); });'> click to remove </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2019" }, { "code": null, "e": 168, "s": 28, "text": "Given a div element. The task is to remove it with a fadeOut effect using JQuery. Here are few methods discussed.First few methods to know." }, { "code": null, "e": 1009, "s": 168, "text": "jQuery text() Method:This method sets/returns the text content of the selected elements.If this method is used to return content, it provides the text content of all matched elements (HTML tags will be removed).If this method is used to set content, it replace the content of ALL matched elements.Syntax:Returns text content:$(selector).text()\nSets text content:$(selector).text(content)\nSet text content using a function:$(selector).text(function(index, curContent))\nParameters:content: This parameter is required. It specifies the new text content for the selected elements.function(index, curContent): This parameter is optional. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements." }, { "code": null, "e": 1050, "s": 1009, "text": "Returns text content:$(selector).text()\n" }, { "code": null, "e": 1070, "s": 1050, "text": "$(selector).text()\n" }, { "code": null, "e": 1115, "s": 1070, "text": "Sets text content:$(selector).text(content)\n" }, { "code": null, "e": 1142, "s": 1115, "text": "$(selector).text(content)\n" }, { "code": null, "e": 1223, "s": 1142, "text": "Set text content using a function:$(selector).text(function(index, curContent))\n" }, { "code": null, "e": 1270, "s": 1223, "text": "$(selector).text(function(index, curContent))\n" }, { "code": null, "e": 1282, "s": 1270, "text": "Parameters:" }, { "code": null, "e": 1380, "s": 1282, "text": "content: This parameter is required. It specifies the new text content for the selected elements." }, { "code": null, "e": 1645, "s": 1380, "text": "function(index, curContent): This parameter is optional. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements." }, { "code": null, "e": 1709, "s": 1645, "text": "index: It returns the index position of the element in the set." }, { "code": null, "e": 1770, "s": 1709, "text": "curContent: It returns current content of selected elements." }, { "code": null, "e": 2486, "s": 1770, "text": "jQuery Effect fadeOut() MethodThis method gradually changes the opacity, for selected elements, from visible to hidden (fading effect).Syntax:$(selector).fadeOut(speed, easing, callback)\nParameters:speed: This parameter is optional. It specifies the speed of the fading effect. Default value = 400 milliseconds.Applicable values.milliseconds“slow”“fast”easing: This parameter is Optional. It specifies the speed of the element in different points of the animation. Default value = “swing”.Applicable values.“swing”: It starts slowly, but faster in the middle.“linear”: It moves in a constant speed.callback: This parameter is optional. It specifies a function to be executed after the fadeOut() method is completed." }, { "code": null, "e": 2532, "s": 2486, "text": "$(selector).fadeOut(speed, easing, callback)\n" }, { "code": null, "e": 2544, "s": 2532, "text": "Parameters:" }, { "code": null, "e": 2700, "s": 2544, "text": "speed: This parameter is optional. It specifies the speed of the fading effect. Default value = 400 milliseconds.Applicable values.milliseconds“slow”“fast”" }, { "code": null, "e": 2713, "s": 2700, "text": "milliseconds" }, { "code": null, "e": 2720, "s": 2713, "text": "“slow”" }, { "code": null, "e": 2727, "s": 2720, "text": "“fast”" }, { "code": null, "e": 2973, "s": 2727, "text": "easing: This parameter is Optional. It specifies the speed of the element in different points of the animation. Default value = “swing”.Applicable values.“swing”: It starts slowly, but faster in the middle.“linear”: It moves in a constant speed." }, { "code": null, "e": 3026, "s": 2973, "text": "“swing”: It starts slowly, but faster in the middle." }, { "code": null, "e": 3066, "s": 3026, "text": "“linear”: It moves in a constant speed." }, { "code": null, "e": 3184, "s": 3066, "text": "callback: This parameter is optional. It specifies a function to be executed after the fadeOut() method is completed." }, { "code": null, "e": 4055, "s": 3184, "text": "jQuery on() MethodThis method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)\nParameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 4114, "s": 4055, "text": "$(selector).on(event, childSelector, data, function, map)\n" }, { "code": null, "e": 4126, "s": 4114, "text": "Parameters:" }, { "code": null, "e": 4331, "s": 4126, "text": "event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In case of multiple event values, those are separated by space. Event must be a valid." }, { "code": null, "e": 4465, "s": 4331, "text": "childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements." }, { "code": null, "e": 4553, "s": 4465, "text": "data: This parameter is optional. It specifies additional data to pass to the function." }, { "code": null, "e": 4647, "s": 4553, "text": "function: This parameter is required. It specifies the function to run when the event occurs." }, { "code": null, "e": 4818, "s": 4647, "text": "map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 5157, "s": 4818, "text": "jQuery remove() MethodThis method removes the selected elements, including all text and child nodes along with the data and events of the selected elements.Syntax:$(selector).remove(selector)\nParameters:event: This parameter is optional. It specifies one or more elements to be removed. Use comma as separator to remove multiple elements." }, { "code": null, "e": 5187, "s": 5157, "text": "$(selector).remove(selector)\n" }, { "code": null, "e": 5199, "s": 5187, "text": "Parameters:" }, { "code": null, "e": 5335, "s": 5199, "text": "event: This parameter is optional. It specifies one or more elements to be removed. Use comma as separator to remove multiple elements." }, { "code": null, "e": 5432, "s": 5335, "text": "Example 1: In this example the div element is removed after fadeOut effect for 300 milliseconds." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | How to FadeOut and Remove a div. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #div { height: 60px; width: 200px; background-color: green; margin: 0 auto; } </style></head> <body style=\"text-align:center;\" id=\"body\"> <h1 id=\"h\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> click the button to remove DIV with fade effect. </p> <div id=\"div\"> </div> <br> <button> click to remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('button').on('click', function(e) { $('#div').fadeOut(300, function() { $('#div').remove(); }); $(\"#GFG_DOWN\").text(\"DIV Removed\"); }); </script></body> </html>", "e": 6519, "s": 5432, "text": null }, { "code": null, "e": 6527, "s": 6519, "text": "Output:" }, { "code": null, "e": 6558, "s": 6527, "text": "Before clicking on the button:" }, { "code": null, "e": 6588, "s": 6558, "text": "After clicking on the button:" }, { "code": null, "e": 6748, "s": 6588, "text": "Example 2: This example is similar to previous. In this example the div element is removed after fadeOut effect for 300 milliseconds with a different approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | How to FadeOut and Remove a div. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #div { height: 60px; width: 200px; background-color: green; margin: 0 auto; } </style></head> <body style=\"text-align:center;\" id=\"body\"> <h1 id=\"h\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> click the button to remove DIV with fade effect. </p> <div id=\"div\"> </div> <br> <button onclick='$(\"#div\").fadeOut(300, function() { $(this).remove(); $(\"#GFG_DOWN\") .text(\"DIV Removed\"); });'> click to remove </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p></body> </html>", "e": 7754, "s": 6748, "text": null }, { "code": null, "e": 7762, "s": 7754, "text": "Output:" }, { "code": null, "e": 7793, "s": 7762, "text": "Before clicking on the button:" }, { "code": null, "e": 7823, "s": 7793, "text": "After clicking on the button:" }, { "code": null, "e": 7839, "s": 7823, "text": "JavaScript-Misc" }, { "code": null, "e": 7850, "s": 7839, "text": "JavaScript" }, { "code": null, "e": 7867, "s": 7850, "text": "Web Technologies" } ]
Python | os.umask() method
26 Jan, 2022 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.umask() method in Python is used to set the current numeric umask value and get the previous umask value. umask stands for user file-creation mode mask. This is used to determine the file permission for newly created files or directories. Syntax: os.umask(mask) Parameter:mask: An integer value denoting a valid umask value. Return Type: This method sets the current umask value and returns an integer value which represents the previous umask value. Code #1: Use of os.umask() method # Python program to explain os.umask() method # importing os module import os # mask# 18 in decimal is# equal to 0o022 in octalmask = 18 # Set the current umask value# and get the previous# umask valueumask = os.umask(mask) # Print the # current and previous # umask valueprint("Current umask:", mask)print("Previous umask:", umask) Current umask: 18 Previous umask: 54 Code #2: Passing an octal value as parameter in os.umask() method # Python program to explain os.umask() method # importing os module import os # Octal value for umask# octal value 0o777 is # 511 in decimalmask = 0o777 # Set the current umask value# and get the previous# umask valueumask = os.umask(mask) # Print the # current and previous # umask valueprint("Current umask:", mask)print("Previous umask:", umask) Current umask: 511 Previous umask: 18 TOD python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jan, 2022" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 356, "s": 247, "text": "os.umask() method in Python is used to set the current numeric umask value and get the previous umask value." }, { "code": null, "e": 489, "s": 356, "text": "umask stands for user file-creation mode mask. This is used to determine the file permission for newly created files or directories." }, { "code": null, "e": 512, "s": 489, "text": "Syntax: os.umask(mask)" }, { "code": null, "e": 575, "s": 512, "text": "Parameter:mask: An integer value denoting a valid umask value." }, { "code": null, "e": 701, "s": 575, "text": "Return Type: This method sets the current umask value and returns an integer value which represents the previous umask value." }, { "code": null, "e": 735, "s": 701, "text": "Code #1: Use of os.umask() method" }, { "code": "# Python program to explain os.umask() method # importing os module import os # mask# 18 in decimal is# equal to 0o022 in octalmask = 18 # Set the current umask value# and get the previous# umask valueumask = os.umask(mask) # Print the # current and previous # umask valueprint(\"Current umask:\", mask)print(\"Previous umask:\", umask) ", "e": 1078, "s": 735, "text": null }, { "code": null, "e": 1116, "s": 1078, "text": "Current umask: 18\nPrevious umask: 54\n" }, { "code": null, "e": 1184, "s": 1118, "text": "Code #2: Passing an octal value as parameter in os.umask() method" }, { "code": "# Python program to explain os.umask() method # importing os module import os # Octal value for umask# octal value 0o777 is # 511 in decimalmask = 0o777 # Set the current umask value# and get the previous# umask valueumask = os.umask(mask) # Print the # current and previous # umask valueprint(\"Current umask:\", mask)print(\"Previous umask:\", umask) ", "e": 1543, "s": 1184, "text": null }, { "code": null, "e": 1582, "s": 1543, "text": "Current umask: 511\nPrevious umask: 18\n" }, { "code": null, "e": 1586, "s": 1582, "text": "TOD" }, { "code": null, "e": 1603, "s": 1586, "text": "python-os-module" }, { "code": null, "e": 1610, "s": 1603, "text": "Python" } ]
List get() method in Java with Examples
11 Dec, 2018 The get() method of List interface in Java is used to get the element present in this list at a given specific index. Syntax : E get(int index) Where, E is the type of element maintained by this List container. Parameter : This method accepts a single parameter index of type integer which represents the index of the element in this list which is to be returned. Return Value: It returns the element at the specified index in the given list. Errors and exception : This method throws an IndexOutOfBoundsException if the index is out of range (index=size()). Below programs illustrate the get() method: Program 1 : // Java code to demonstrate the working of// get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); System.out.println("List: " + arr); // element at index 2 int element = arr.get(2); System.out.println("The element at index 2 is " + element); }} List: [10, 20, 30, 40] The element at index 2 is 30 Program 2 : Program to demonstrate the error. // Java code to demonstrate the error of// get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); try { // Trying to access element at index 8 // which will throw an Exception int element = arr.get(8); } catch (Exception e) { System.out.println(e); } }} java.lang.IndexOutOfBoundsException: Index: 8, Size: 4 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int) Java-Collections Java-Functions java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Dec, 2018" }, { "code": null, "e": 171, "s": 53, "text": "The get() method of List interface in Java is used to get the element present in this list at a given specific index." }, { "code": null, "e": 180, "s": 171, "text": "Syntax :" }, { "code": null, "e": 266, "s": 180, "text": "E get(int index)\n\nWhere, E is the type of element maintained\nby this List container.\n" }, { "code": null, "e": 419, "s": 266, "text": "Parameter : This method accepts a single parameter index of type integer which represents the index of the element in this list which is to be returned." }, { "code": null, "e": 498, "s": 419, "text": "Return Value: It returns the element at the specified index in the given list." }, { "code": null, "e": 614, "s": 498, "text": "Errors and exception : This method throws an IndexOutOfBoundsException if the index is out of range (index=size())." }, { "code": null, "e": 658, "s": 614, "text": "Below programs illustrate the get() method:" }, { "code": null, "e": 670, "s": 658, "text": "Program 1 :" }, { "code": "// Java code to demonstrate the working of// get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); System.out.println(\"List: \" + arr); // element at index 2 int element = arr.get(2); System.out.println(\"The element at index 2 is \" + element); }}", "e": 1255, "s": 670, "text": null }, { "code": null, "e": 1308, "s": 1255, "text": "List: [10, 20, 30, 40]\nThe element at index 2 is 30\n" }, { "code": null, "e": 1354, "s": 1308, "text": "Program 2 : Program to demonstrate the error." }, { "code": "// Java code to demonstrate the error of// get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); try { // Trying to access element at index 8 // which will throw an Exception int element = arr.get(8); } catch (Exception e) { System.out.println(e); } }}", "e": 1986, "s": 1354, "text": null }, { "code": null, "e": 2042, "s": 1986, "text": "java.lang.IndexOutOfBoundsException: Index: 8, Size: 4\n" }, { "code": null, "e": 2124, "s": 2042, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int)" }, { "code": null, "e": 2141, "s": 2124, "text": "Java-Collections" }, { "code": null, "e": 2156, "s": 2141, "text": "Java-Functions" }, { "code": null, "e": 2166, "s": 2156, "text": "java-list" }, { "code": null, "e": 2171, "s": 2166, "text": "Java" }, { "code": null, "e": 2176, "s": 2171, "text": "Java" }, { "code": null, "e": 2193, "s": 2176, "text": "Java-Collections" } ]
HTML | DOM Input Image disabled Property
21 Jun, 2022 The HTML DOM Input Image disabled Property is used to set or return the boolean value that represents an image field should be disabled or not. By default, the disabled elements are displayed in gray and are unusable and unclickable. Syntax: It returns the disabled property. imageObject.disabled It is used to set the disabled property. imageObject.disabled = true|false Property values: This property accepts two parameter which are mentioned above and described below: true: It specifies the image field is disabled. false: It specifies the image field is not disabled. Return value: It returns a boolean value i.e. true if the image field is disabled or false if the image field is not disabled. Example 1: This example returns the value of disabled proper html <!DOCTYPE html><html> <head> <title> HTML DOM Input Image Disabled property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> DOM Input Image Disabled Property </h4> <input id="myImage" formEnctype="application/x-www-form-urlencoded" type="image" formtarget="#" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="48" height="48" formMethod="post" disabled> <br> <br> <button onclick="my_geek()">Submit </button> <h2 id="Geek_h" style="color:green;"></h2> <script> function my_geek() { // Return disabled Property var txt = document.getElementById( "myImage").disabled; document.getElementById( "Geek_h").innerHTML = txt; } </script></body> </html> Output: Before Clicking On Button: After Clicking On Button: Example 2: This Example sets the value of the Disabled Property. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Image Disabled property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> DOM Input Image Disabled Property </h4> <input id="myImage" formEnctype="application/x-www-form-urlencoded" type="image" formtarget="#" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="48" height="48" formMethod="post" disabled> <br> <br> <button onclick="my_geek()">Submit </button> <h2 id="Geek_h" style="color:green;"></h2> <script> function my_geek() { // set Disabled Property. var txt = document.getElementById( "myImage").disabled = false; document.getElementById( "Geek_h").innerHTML = txt; } </script></body> </html> Output: Before Clicking On Button: After Clicking On Button: Supported Browsers: The browsers supported by HTML DOM Input Image disabled Property are listed below: Google Chrome 10.0 Firefox 4.0 Opera 11.0 Safari 5.1 shubham_singh hritikbhatnagar2182 HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 263, "s": 28, "text": "The HTML DOM Input Image disabled Property is used to set or return the boolean value that represents an image field should be disabled or not. By default, the disabled elements are displayed in gray and are unusable and unclickable. " }, { "code": null, "e": 271, "s": 263, "text": "Syntax:" }, { "code": null, "e": 305, "s": 271, "text": "It returns the disabled property." }, { "code": null, "e": 326, "s": 305, "text": "imageObject.disabled" }, { "code": null, "e": 367, "s": 326, "text": "It is used to set the disabled property." }, { "code": null, "e": 401, "s": 367, "text": "imageObject.disabled = true|false" }, { "code": null, "e": 501, "s": 401, "text": "Property values: This property accepts two parameter which are mentioned above and described below:" }, { "code": null, "e": 549, "s": 501, "text": "true: It specifies the image field is disabled." }, { "code": null, "e": 602, "s": 549, "text": "false: It specifies the image field is not disabled." }, { "code": null, "e": 730, "s": 602, "text": "Return value: It returns a boolean value i.e. true if the image field is disabled or false if the image field is not disabled. " }, { "code": null, "e": 792, "s": 730, "text": "Example 1: This example returns the value of disabled proper " }, { "code": null, "e": 797, "s": 792, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Image Disabled property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> DOM Input Image Disabled Property </h4> <input id=\"myImage\" formEnctype=\"application/x-www-form-urlencoded\" type=\"image\" formtarget=\"#\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"48\" height=\"48\" formMethod=\"post\" disabled> <br> <br> <button onclick=\"my_geek()\">Submit </button> <h2 id=\"Geek_h\" style=\"color:green;\"></h2> <script> function my_geek() { // Return disabled Property var txt = document.getElementById( \"myImage\").disabled; document.getElementById( \"Geek_h\").innerHTML = txt; } </script></body> </html>", "e": 1699, "s": 797, "text": null }, { "code": null, "e": 1707, "s": 1699, "text": "Output:" }, { "code": null, "e": 1734, "s": 1707, "text": "Before Clicking On Button:" }, { "code": null, "e": 1762, "s": 1736, "text": "After Clicking On Button:" }, { "code": null, "e": 1830, "s": 1764, "text": "Example 2: This Example sets the value of the Disabled Property. " }, { "code": null, "e": 1835, "s": 1830, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Image Disabled property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> DOM Input Image Disabled Property </h4> <input id=\"myImage\" formEnctype=\"application/x-www-form-urlencoded\" type=\"image\" formtarget=\"#\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"48\" height=\"48\" formMethod=\"post\" disabled> <br> <br> <button onclick=\"my_geek()\">Submit </button> <h2 id=\"Geek_h\" style=\"color:green;\"></h2> <script> function my_geek() { // set Disabled Property. var txt = document.getElementById( \"myImage\").disabled = false; document.getElementById( \"Geek_h\").innerHTML = txt; } </script></body> </html>", "e": 2744, "s": 1835, "text": null }, { "code": null, "e": 2752, "s": 2744, "text": "Output:" }, { "code": null, "e": 2779, "s": 2752, "text": "Before Clicking On Button:" }, { "code": null, "e": 2807, "s": 2781, "text": "After Clicking On Button:" }, { "code": null, "e": 2912, "s": 2809, "text": "Supported Browsers: The browsers supported by HTML DOM Input Image disabled Property are listed below:" }, { "code": null, "e": 2931, "s": 2912, "text": "Google Chrome 10.0" }, { "code": null, "e": 2943, "s": 2931, "text": "Firefox 4.0" }, { "code": null, "e": 2954, "s": 2943, "text": "Opera 11.0" }, { "code": null, "e": 2965, "s": 2954, "text": "Safari 5.1" }, { "code": null, "e": 2979, "s": 2965, "text": "shubham_singh" }, { "code": null, "e": 2999, "s": 2979, "text": "hritikbhatnagar2182" }, { "code": null, "e": 3008, "s": 2999, "text": "HTML-DOM" }, { "code": null, "e": 3013, "s": 3008, "text": "HTML" }, { "code": null, "e": 3030, "s": 3013, "text": "Web Technologies" }, { "code": null, "e": 3035, "s": 3030, "text": "HTML" } ]
GridView in Android with Example
06 Sep, 2021 A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array. The adapter is used for displaying this data, setAdapter() method is used to join the adapter with GridView. The main function of the adapter in GridView is to fetch data from a database or array and insert each piece of data in an appropriate item that will be displayed in GridView. This is how the GridView structure looks like. Note that we are going to implement this project using the Java language. android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid. android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView. android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView. Now let us see an example in which we will implement a simple GridView in Android App. In the GridView, we are now displaying the list of courses available on GeeksforGeeks. Step 1: Creating a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add google repository in the build.gradle file of the application project. buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 3: Modify the activity_main.xml file Add GridView to the activity_main.xml file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- android:numColumns=2 is the number of columns for Grid View android:horizontalSpacing is the space between horizontal grid items.--> <GridView android:id="@+id/idGVcourses" android:layout_width="match_parent" android:layout_height="match_parent" android:horizontalSpacing="6dp" android:numColumns="2" android:verticalSpacing="6dp" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Create an XML layout file for each item of GridView Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. Below is the code for the card_item.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--XML implementation of Card Layout--><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="120dp" android:layout_gravity="center" android:layout_margin="5dp" app:cardCornerRadius="5dp" app:cardElevation="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/idIVcourse" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/idTVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/app_name" android:textAlignment="center" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 5: Create a Modal Class for storing Data Modal Class is the JAVA Class that handles data to be added in each GridView item of GridView. For Creating Modal Class. Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseModel. Below is the code for the CourseModel.java file. Java public class CourseModel { // string course_name for storing course_name // and imgid for storing image id. private String course_name; private int imgid; public CourseModel(String course_name, int imgid) { this.course_name = course_name; this.imgid = imgid; } public String getCourse_name() { return course_name; } public void setCourse_name(String course_name) { this.course_name = course_name; } public int getImgid() { return imgid; } public void setImgid(int imgid) { this.imgid = imgid; }} Step 6: Create an Adapter Class Adapter Class adds the data from Modal Class in each item of GridView which is to be displayed on the screen. For Creating Adapter Class. Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter.java file. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter<CourseModel> { public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) { super(context, 0, courseModelArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; }} Step 7: Modify the MainActivity.java file Now in this file, we will perform all backend operations that will be adding data to GridView. Below is the code for the MainActivity.java file. Java import android.os.Bundle;import android.widget.GridView;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>(); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList); coursesGV.setAdapter(adapter); }} Output: hemantjain99 android Android-View Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Android Project folder Structure Broadcast Receiver in Android With Example Navigation Drawer in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Sep, 2021" }, { "code": null, "e": 629, "s": 54, "text": "A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array. The adapter is used for displaying this data, setAdapter() method is used to join the adapter with GridView. The main function of the adapter in GridView is to fetch data from a database or array and insert each piece of data in an appropriate item that will be displayed in GridView. This is how the GridView structure looks like. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 755, "s": 629, "text": "android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid." }, { "code": null, "e": 860, "s": 755, "text": "android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView." }, { "code": null, "e": 961, "s": 860, "text": "android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView." }, { "code": null, "e": 1137, "s": 961, "text": "Now let us see an example in which we will implement a simple GridView in Android App. In the GridView, we are now displaying the list of courses available on GeeksforGeeks. " }, { "code": null, "e": 1168, "s": 1137, "text": "Step 1: Creating a New Project" }, { "code": null, "e": 1330, "s": 1168, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1413, "s": 1330, "text": "Step 2: Add google repository in the build.gradle file of the application project." }, { "code": null, "e": 1427, "s": 1413, "text": "buildscript {" }, { "code": null, "e": 1443, "s": 1427, "text": " repositories {" }, { "code": null, "e": 1456, "s": 1443, "text": " google()" }, { "code": null, "e": 1475, "s": 1456, "text": " mavenCentral()" }, { "code": null, "e": 1477, "s": 1475, "text": "}" }, { "code": null, "e": 1584, "s": 1477, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 1598, "s": 1584, "text": "allprojects {" }, { "code": null, "e": 1614, "s": 1598, "text": " repositories {" }, { "code": null, "e": 1627, "s": 1614, "text": " google()" }, { "code": null, "e": 1645, "s": 1627, "text": " mavenCentral()" }, { "code": null, "e": 1648, "s": 1645, "text": " }" }, { "code": null, "e": 1650, "s": 1648, "text": "}" }, { "code": null, "e": 1692, "s": 1650, "text": "Step 3: Modify the activity_main.xml file" }, { "code": null, "e": 1786, "s": 1692, "text": "Add GridView to the activity_main.xml file. Below is the code for the activity_main.xml file." }, { "code": null, "e": 1790, "s": 1786, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- android:numColumns=2 is the number of columns for Grid View android:horizontalSpacing is the space between horizontal grid items.--> <GridView android:id=\"@+id/idGVcourses\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:horizontalSpacing=\"6dp\" android:numColumns=\"2\" android:verticalSpacing=\"6dp\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2561, "s": 1790, "text": null }, { "code": null, "e": 2621, "s": 2561, "text": "Step 4: Create an XML layout file for each item of GridView" }, { "code": null, "e": 2840, "s": 2621, "text": "Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. Below is the code for the card_item.xml file." }, { "code": null, "e": 2844, "s": 2840, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--XML implementation of Card Layout--><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"120dp\" android:layout_gravity=\"center\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"5dp\" app:cardElevation=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVcourse\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_gravity=\"center\" android:src=\"@mipmap/ic_launcher\" /> <TextView android:id=\"@+id/idTVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/app_name\" android:textAlignment=\"center\" /> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 3943, "s": 2844, "text": null }, { "code": null, "e": 3989, "s": 3943, "text": "Step 5: Create a Modal Class for storing Data" }, { "code": null, "e": 4111, "s": 3989, "text": "Modal Class is the JAVA Class that handles data to be added in each GridView item of GridView. For Creating Modal Class. " }, { "code": null, "e": 4176, "s": 4111, "text": "Now click on app > java > apps package name > Right-Click on it." }, { "code": null, "e": 4208, "s": 4176, "text": "Then Click on New > Java Class." }, { "code": null, "e": 4299, "s": 4208, "text": "Name your Java Class file as CourseModel. Below is the code for the CourseModel.java file." }, { "code": null, "e": 4304, "s": 4299, "text": "Java" }, { "code": "public class CourseModel { // string course_name for storing course_name // and imgid for storing image id. private String course_name; private int imgid; public CourseModel(String course_name, int imgid) { this.course_name = course_name; this.imgid = imgid; } public String getCourse_name() { return course_name; } public void setCourse_name(String course_name) { this.course_name = course_name; } public int getImgid() { return imgid; } public void setImgid(int imgid) { this.imgid = imgid; }}", "e": 4890, "s": 4304, "text": null }, { "code": null, "e": 4922, "s": 4890, "text": "Step 6: Create an Adapter Class" }, { "code": null, "e": 5060, "s": 4922, "text": "Adapter Class adds the data from Modal Class in each item of GridView which is to be displayed on the screen. For Creating Adapter Class." }, { "code": null, "e": 5125, "s": 5060, "text": "Now click on app > java > apps package name > Right-Click on it." }, { "code": null, "e": 5157, "s": 5125, "text": "Then Click on New > Java Class." }, { "code": null, "e": 5257, "s": 5157, "text": "Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter.java file. " }, { "code": null, "e": 5262, "s": 5257, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter<CourseModel> { public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) { super(context, 0, courseModelArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; }}", "e": 6525, "s": 5262, "text": null }, { "code": null, "e": 6568, "s": 6525, "text": "Step 7: Modify the MainActivity.java file " }, { "code": null, "e": 6713, "s": 6568, "text": "Now in this file, we will perform all backend operations that will be adding data to GridView. Below is the code for the MainActivity.java file." }, { "code": null, "e": 6718, "s": 6713, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.GridView;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>(); courseModelArrayList.add(new CourseModel(\"DSA\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel(\"JAVA\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel(\"C++\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel(\"Python\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel(\"Javascript\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel(\"DSA\", R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList); coursesGV.setAdapter(adapter); }}", "e": 7854, "s": 6718, "text": null }, { "code": null, "e": 7862, "s": 7854, "text": "Output:" }, { "code": null, "e": 7875, "s": 7862, "text": "hemantjain99" }, { "code": null, "e": 7883, "s": 7875, "text": "android" }, { "code": null, "e": 7896, "s": 7883, "text": "Android-View" }, { "code": null, "e": 7903, "s": 7896, "text": "Picked" }, { "code": null, "e": 7911, "s": 7903, "text": "Android" }, { "code": null, "e": 7916, "s": 7911, "text": "Java" }, { "code": null, "e": 7921, "s": 7916, "text": "Java" }, { "code": null, "e": 7929, "s": 7921, "text": "Android" }, { "code": null, "e": 8027, "s": 7929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8059, "s": 8027, "text": "Android SDK and it's Components" }, { "code": null, "e": 8090, "s": 8059, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 8123, "s": 8090, "text": "Android Project folder Structure" }, { "code": null, "e": 8166, "s": 8123, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 8195, "s": 8166, "text": "Navigation Drawer in Android" }, { "code": null, "e": 8210, "s": 8195, "text": "Arrays in Java" }, { "code": null, "e": 8254, "s": 8210, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8276, "s": 8254, "text": "For-each loop in Java" }, { "code": null, "e": 8301, "s": 8276, "text": "Reverse a string in Java" } ]
Python PIL | blend() method
25 Jun, 2019 Syntax: PIL.Image.blend(image1, image2, alpha). Parameter:image1: first imageimage2: second image, must have the same mode and size as the first image.alpha: The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range. Image1: Image2: # Importing Image module from PIL package from PIL import Image # creating a image1 object and convert it to mode 'P'im1 = Image.open(r"C:\Users\sadow984\Desktop\i2.PNG").convert('L') # creating a image2 object and convert it to mode 'P'im2 = Image.open(r"C:\Users\sadow984\Desktop\c2.PNG").convert('L') # alpha is 0.0, a copy of the first image is returnedim3 = Image.blend(im1, im2, 0.0) # to show specified image im3.show() Output: # Importing Image module from PIL package from PIL import Image # creating a image1 object and convert it to mode 'P'im1 = Image.open(r"C:\Users\sadow984\Desktop\i2.PNG").convert('L') # creating a image2 object and convert it to mode 'P' im2 = Image.open(r"C:\Users\sadow984\Desktop\c2.PNG").convert('L') # alpha is 1.0, a copy of the second image is returnedim3 = Image.blend(im1, im2, 0.0) # to show specified image im3.show() Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jun, 2019" }, { "code": null, "e": 100, "s": 52, "text": "Syntax: PIL.Image.blend(image1, image2, alpha)." }, { "code": null, "e": 475, "s": 100, "text": "Parameter:image1: first imageimage2: second image, must have the same mode and size as the first image.alpha: The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range." }, { "code": null, "e": 483, "s": 475, "text": "Image1:" }, { "code": null, "e": 491, "s": 483, "text": "Image2:" }, { "code": "# Importing Image module from PIL package from PIL import Image # creating a image1 object and convert it to mode 'P'im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i2.PNG\").convert('L') # creating a image2 object and convert it to mode 'P'im2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\c2.PNG\").convert('L') # alpha is 0.0, a copy of the first image is returnedim3 = Image.blend(im1, im2, 0.0) # to show specified image im3.show()", "e": 922, "s": 491, "text": null }, { "code": null, "e": 930, "s": 922, "text": "Output:" }, { "code": "# Importing Image module from PIL package from PIL import Image # creating a image1 object and convert it to mode 'P'im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i2.PNG\").convert('L') # creating a image2 object and convert it to mode 'P' im2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\c2.PNG\").convert('L') # alpha is 1.0, a copy of the second image is returnedim3 = Image.blend(im1, im2, 0.0) # to show specified image im3.show()", "e": 1363, "s": 930, "text": null }, { "code": null, "e": 1371, "s": 1363, "text": "Output:" }, { "code": null, "e": 1386, "s": 1371, "text": "python-utility" }, { "code": null, "e": 1393, "s": 1386, "text": "Python" } ]
Find Prime Adam integers in the given range [L, R]
08 Nov, 2021 Given two numbers L and R which signifies a range [L, R], the task is to print all the prime adam integers in this range.Note: A number which is both prime, as well as adam, is known as a prime adam number. Examples: Input: L = 5, R = 100 Output: 11 13 31 Explanation: The three numbers 11, 13, 31 are prime. They are also adam numbers. Input: L = 70, R = 50 Output: Invalid Input Approach: The idea used in this problem is to first check whether a number is prime or not. If it is prime, then check whether it is an adam number of not: Iterate through the given range [L, R]. For every number, check if the number is prime or not. If it is a prime, then check whether the number is an adam number or not. If a number is both prime and adam, then print the number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find all prime// adam numbers in the given range#include <bits/stdc++.h>using namespace std; int reverse(int a){ int rev = 0; while (a != 0) { int r = a % 10; // Reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev);} // Function to check if a number// is a prime or notint prime(int a){ int k = 0; // Iterating till the number for(int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are // no factors of the number other // than 1 or itself if (k == 1) { return (0); } else { return (1); }} // Function to check whether a number// is an adam number or notint adam(int a){ // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the // number and the square of its // reverse are equal or not if (s1 == r2) { return (1); } else { return (0); }} // Function to find all the prime// adam numbers in the given rangevoid find(int m, int n){ // If the first number is greater // than the second number, // print invalid if (m > n) { cout << " INVALID INPUT " << endl; } else { int c = 0; // Iterating through all the // numbers in the given range for(int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { cout << i << "\t"; } } }} // Driver codeint main(){ int L = 5, R = 100; find(L, R); return 0;} // This code is contributed by Amit Katiyar // Java program to find all prime// adam numbers in the given rangeimport java.io.*; class GFG { public static int reverse(int a) { int rev = 0; while (a != 0) { int r = a % 10; // reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev); } // Function to check if a number // is a prime or not public static int prime(int a) { int k = 0; // Iterating till the number for (int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); } } // Function to check whether a number // is an adam number or not public static int adam(int a) { // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the number // and the square of its reverse // are equal or not if (s1 == r2) { return (1); } else { return (0); } } // Function to find all the prime // adam numbers in the given range public static void find(int m, int n) { // If the first number is greater // than the second number, // print invalid if (m > n) { System.out.println(" INVALID INPUT "); } else { int c = 0; // Iterating through all the numbers // in the given range for (int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { System.out.print(i + "\t"); } } } } // Driver code public static void main(String[] args) { int L = 5, R = 100; find(L, R); }} # Python3 program to find all prime# adam numbers in the given range def reverse(a): rev = 0; while (a != 0): r = a % 10; # Reversing a number by taking # remainder at a time rev = rev * 10 + r; a = a // 10; return(rev); # Function to check if a number# is a prime or notdef prime(a): k = 0; # Iterating till the number for i in range(2, a): # Checking for factors if (a % i == 0): k = 1; break; # Returning 1 if the there are # no factors of the number other # than 1 or itself if (k == 1): return (0); else: return (1); # Function to check whether a number# is an adam number or notdef adam(a): # Reversing given number r1 = reverse(a); # Squaring given number s1 = a * a; # Squaring reversed number s2 = r1 * r1; # Reversing the square of the # reversed number r2 = reverse(s2); # Checking if the square of the # number and the square of its # reverse are equal or not if (s1 == r2): return (1); else: return (0); # Function to find all the prime# adam numbers in the given rangedef find(m, n): # If the first number is greater # than the second number, # print invalid if (m > n): print("INVALID INPUT\n"); else: c = 0; # Iterating through all the # numbers in the given range for i in range(m, n): # Checking for prime number l = prime(i); # Checking for Adam number k = adam(i); if ((l == 1) and (k == 1)): print(i, "\t", end = " "); # Driver codeL = 5; R = 100;find(L, R); # This code is contributed by Code_Mech // C# program to find all prime// adam numbers in the given rangeusing System; class GFG{ public static int reverse(int a){ int rev = 0; while (a != 0) { int r = a % 10; // Reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev);} // Function to check if a number// is a prime or notpublic static int prime(int a){ int k = 0; // Iterating till the number for(int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); }} // Function to check whether a number// is an adam number or notpublic static int adam(int a){ // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the // number and the square of its // reverse are equal or not if (s1 == r2) { return (1); } else { return (0); }} // Function to find all the prime// adam numbers in the given rangepublic static void find(int m, int n){ // If the first number is greater // than the second number, // print invalid if (m > n) { Console.WriteLine("INVALID INPUT"); } else { // Iterating through all the numbers // in the given range for(int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { Console.Write(i + "\t"); } } }} // Driver codepublic static void Main(String[] args){ int L = 5, R = 100; find(L, R);}} // This code is contributed by Rohit_ranjan <script> // JavaScript program to find all prime // adam numbers in the given range function reverse(a) { let rev = 0; while (a != 0) { let r = a % 10; // reversing a number by taking // remainder at a time rev = rev * 10 + r; a = parseInt(a / 10, 10); } return (rev); } // Function to check if a number // is a prime or not function prime(a) { let k = 0; // Iterating till the number for (let i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); } } // Function to check whether a number // is an adam number or not function adam(a) { // Reversing given number let r1 = reverse(a); // Squaring given number let s1 = a * a; // Squaring reversed number let s2 = r1 * r1; // Reversing the square of the // reversed number let r2 = reverse(s2); // Checking if the square of the number // and the square of its reverse // are equal or not if (s1 == r2) { return (1); } else { return (0); } } // Function to find all the prime // adam numbers in the given range function find(m, n) { // If the first number is greater // than the second number, // print invalid if (m > n) { document.write(" INVALID INPUT " + "</br>"); } else { let c = 0; // Iterating through all the numbers // in the given range for (let i = m; i <= n; i++) { // Checking for prime number let l = prime(i); // Checking for Adam number let k = adam(i); if ((l == 1) && (k == 1)) { document.write(i + " "); } } } } let L = 5, R = 100; find(L, R); </script> Time Complexity: O(N2), where N is the maximum number R. Auxiliary Space: O(1) Rohit_ranjan amit143katiyar Code_Mech divyeshrabadiya07 sushmitamittal1329 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2021" }, { "code": null, "e": 247, "s": 28, "text": "Given two numbers L and R which signifies a range [L, R], the task is to print all the prime adam integers in this range.Note: A number which is both prime, as well as adam, is known as a prime adam number. Examples: " }, { "code": null, "e": 413, "s": 247, "text": "Input: L = 5, R = 100 Output: 11 13 31 Explanation: The three numbers 11, 13, 31 are prime. They are also adam numbers. Input: L = 70, R = 50 Output: Invalid Input " }, { "code": null, "e": 573, "s": 415, "text": "Approach: The idea used in this problem is to first check whether a number is prime or not. If it is prime, then check whether it is an adam number of not: " }, { "code": null, "e": 613, "s": 573, "text": "Iterate through the given range [L, R]." }, { "code": null, "e": 668, "s": 613, "text": "For every number, check if the number is prime or not." }, { "code": null, "e": 742, "s": 668, "text": "If it is a prime, then check whether the number is an adam number or not." }, { "code": null, "e": 801, "s": 742, "text": "If a number is both prime and adam, then print the number." }, { "code": null, "e": 854, "s": 801, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 858, "s": 854, "text": "C++" }, { "code": null, "e": 863, "s": 858, "text": "Java" }, { "code": null, "e": 871, "s": 863, "text": "Python3" }, { "code": null, "e": 874, "s": 871, "text": "C#" }, { "code": null, "e": 885, "s": 874, "text": "Javascript" }, { "code": "// C++ program to find all prime// adam numbers in the given range#include <bits/stdc++.h>using namespace std; int reverse(int a){ int rev = 0; while (a != 0) { int r = a % 10; // Reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev);} // Function to check if a number// is a prime or notint prime(int a){ int k = 0; // Iterating till the number for(int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are // no factors of the number other // than 1 or itself if (k == 1) { return (0); } else { return (1); }} // Function to check whether a number// is an adam number or notint adam(int a){ // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the // number and the square of its // reverse are equal or not if (s1 == r2) { return (1); } else { return (0); }} // Function to find all the prime// adam numbers in the given rangevoid find(int m, int n){ // If the first number is greater // than the second number, // print invalid if (m > n) { cout << \" INVALID INPUT \" << endl; } else { int c = 0; // Iterating through all the // numbers in the given range for(int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { cout << i << \"\\t\"; } } }} // Driver codeint main(){ int L = 5, R = 100; find(L, R); return 0;} // This code is contributed by Amit Katiyar", "e": 2947, "s": 885, "text": null }, { "code": "// Java program to find all prime// adam numbers in the given rangeimport java.io.*; class GFG { public static int reverse(int a) { int rev = 0; while (a != 0) { int r = a % 10; // reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev); } // Function to check if a number // is a prime or not public static int prime(int a) { int k = 0; // Iterating till the number for (int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); } } // Function to check whether a number // is an adam number or not public static int adam(int a) { // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the number // and the square of its reverse // are equal or not if (s1 == r2) { return (1); } else { return (0); } } // Function to find all the prime // adam numbers in the given range public static void find(int m, int n) { // If the first number is greater // than the second number, // print invalid if (m > n) { System.out.println(\" INVALID INPUT \"); } else { int c = 0; // Iterating through all the numbers // in the given range for (int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { System.out.print(i + \"\\t\"); } } } } // Driver code public static void main(String[] args) { int L = 5, R = 100; find(L, R); }}", "e": 5321, "s": 2947, "text": null }, { "code": "# Python3 program to find all prime# adam numbers in the given range def reverse(a): rev = 0; while (a != 0): r = a % 10; # Reversing a number by taking # remainder at a time rev = rev * 10 + r; a = a // 10; return(rev); # Function to check if a number# is a prime or notdef prime(a): k = 0; # Iterating till the number for i in range(2, a): # Checking for factors if (a % i == 0): k = 1; break; # Returning 1 if the there are # no factors of the number other # than 1 or itself if (k == 1): return (0); else: return (1); # Function to check whether a number# is an adam number or notdef adam(a): # Reversing given number r1 = reverse(a); # Squaring given number s1 = a * a; # Squaring reversed number s2 = r1 * r1; # Reversing the square of the # reversed number r2 = reverse(s2); # Checking if the square of the # number and the square of its # reverse are equal or not if (s1 == r2): return (1); else: return (0); # Function to find all the prime# adam numbers in the given rangedef find(m, n): # If the first number is greater # than the second number, # print invalid if (m > n): print(\"INVALID INPUT\\n\"); else: c = 0; # Iterating through all the # numbers in the given range for i in range(m, n): # Checking for prime number l = prime(i); # Checking for Adam number k = adam(i); if ((l == 1) and (k == 1)): print(i, \"\\t\", end = \" \"); # Driver codeL = 5; R = 100;find(L, R); # This code is contributed by Code_Mech", "e": 7040, "s": 5321, "text": null }, { "code": "// C# program to find all prime// adam numbers in the given rangeusing System; class GFG{ public static int reverse(int a){ int rev = 0; while (a != 0) { int r = a % 10; // Reversing a number by taking // remainder at a time rev = rev * 10 + r; a = a / 10; } return (rev);} // Function to check if a number// is a prime or notpublic static int prime(int a){ int k = 0; // Iterating till the number for(int i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); }} // Function to check whether a number// is an adam number or notpublic static int adam(int a){ // Reversing given number int r1 = reverse(a); // Squaring given number int s1 = a * a; // Squaring reversed number int s2 = r1 * r1; // Reversing the square of the // reversed number int r2 = reverse(s2); // Checking if the square of the // number and the square of its // reverse are equal or not if (s1 == r2) { return (1); } else { return (0); }} // Function to find all the prime// adam numbers in the given rangepublic static void find(int m, int n){ // If the first number is greater // than the second number, // print invalid if (m > n) { Console.WriteLine(\"INVALID INPUT\"); } else { // Iterating through all the numbers // in the given range for(int i = m; i <= n; i++) { // Checking for prime number int l = prime(i); // Checking for Adam number int k = adam(i); if ((l == 1) && (k == 1)) { Console.Write(i + \"\\t\"); } } }} // Driver codepublic static void Main(String[] args){ int L = 5, R = 100; find(L, R);}} // This code is contributed by Rohit_ranjan", "e": 9153, "s": 7040, "text": null }, { "code": "<script> // JavaScript program to find all prime // adam numbers in the given range function reverse(a) { let rev = 0; while (a != 0) { let r = a % 10; // reversing a number by taking // remainder at a time rev = rev * 10 + r; a = parseInt(a / 10, 10); } return (rev); } // Function to check if a number // is a prime or not function prime(a) { let k = 0; // Iterating till the number for (let i = 2; i < a; i++) { // Checking for factors if (a % i == 0) { k = 1; break; } } // Returning 1 if the there are no factors // of the number other than 1 or itself if (k == 1) { return (0); } else { return (1); } } // Function to check whether a number // is an adam number or not function adam(a) { // Reversing given number let r1 = reverse(a); // Squaring given number let s1 = a * a; // Squaring reversed number let s2 = r1 * r1; // Reversing the square of the // reversed number let r2 = reverse(s2); // Checking if the square of the number // and the square of its reverse // are equal or not if (s1 == r2) { return (1); } else { return (0); } } // Function to find all the prime // adam numbers in the given range function find(m, n) { // If the first number is greater // than the second number, // print invalid if (m > n) { document.write(\" INVALID INPUT \" + \"</br>\"); } else { let c = 0; // Iterating through all the numbers // in the given range for (let i = m; i <= n; i++) { // Checking for prime number let l = prime(i); // Checking for Adam number let k = adam(i); if ((l == 1) && (k == 1)) { document.write(i + \" \"); } } } } let L = 5, R = 100; find(L, R); </script>", "e": 11436, "s": 9153, "text": null }, { "code": null, "e": 11494, "s": 11436, "text": "Time Complexity: O(N2), where N is the maximum number R. " }, { "code": null, "e": 11517, "s": 11494, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 11530, "s": 11517, "text": "Rohit_ranjan" }, { "code": null, "e": 11545, "s": 11530, "text": "amit143katiyar" }, { "code": null, "e": 11555, "s": 11545, "text": "Code_Mech" }, { "code": null, "e": 11573, "s": 11555, "text": "divyeshrabadiya07" }, { "code": null, "e": 11592, "s": 11573, "text": "sushmitamittal1329" }, { "code": null, "e": 11605, "s": 11592, "text": "Mathematical" }, { "code": null, "e": 11624, "s": 11605, "text": "School Programming" }, { "code": null, "e": 11637, "s": 11624, "text": "Mathematical" } ]
AutoVIML: Automating Machine Learning | by Himanshu Sharma | Towards Data Science
Machine Learning provides the advantage of studying algorithms which improves automatically with experience. There are ’n’ numbers of machine learning algorithms and techniques and generally, we need to test most of them in order to find the best prediction model for our dataset which has the highest accuracy. Most of the machine learning methods like regression techniques, classification techniques, and other models are defined in Sklearn but in order to select which technique is best for our problem statement or our dataset, we need to try out all these models along with hyperparameter tuning and find out the best performing model. This takes a lot of time and effort which can be reduced using a python package named AutoVIML. AutoVIML is an open-source python package that makes machine learning easy. What it does is, it renders your data through different machine learning models and finds out the best model with the highest accuracy for a given dataset. There is no need to preprocess the dataset to pass it to AutoVIML it automatically cleans your data, helps you in classifying the variables, performs feature reduction, can handle data with different types of variables like text, number, date, etc in a single model. In this article, we will see how we can use AutoVIML in order to reduce the time and effort we put to create machine learning models. We will see what are the different parameters which we use in AutoVIML and what changes they have on our prediction. Like any other python library, we will use pip to install autoviml. pip install autoviml from autoviml.Auto_ViML import Auto_ViML For exploring AutoVIML you can use any dataset, here I am going to use a Heart Disease-related dataset which you can download from Kaggle. This dataset contains different attributes and the target variable. import pandas as pddf = pd.read_csv('heart_d.csv')df Now let us understand how we use autoviml to make a prediction model using this dataset and what parameters are there in AutoVIML. #Basic Example with all parametersmodel, features, trainm, testm = Auto_ViML( train, target, test, sample_submission, hyper_param="GS", feature_reduction=True, scoring_parameter="weighted-f1", KMeans_Featurizer=False, Boosting_Flag=False, Binning_Flag=False, Add_Poly=False, Stacking_Flag=False, Imbalanced_Flag=False, verbose=0,) In the code above we can clearly see how to create the model using AutoVIML and what are the parameters, we can use. Now let us discuss what are these parameters in detail. train: It should contain the location of your dataset or if you have loaded it in a dataframe then the name of the dataframe. In this article we have loaded it in a dataframe named ‘df’ so we will set is as ‘df’.target: It contains the name of the target variable. In our case, the target variable name is “TenYearCHD”.test: It contains the test dataset. We can also leave it blank like this “” if we do not have any test dataset so that it will split the train dataset int train and test.sample_submission: We will leave it empty so that it will automatically create submission in our local directory.hyper_param: We will randomized search cv because it is 3X faster than Grid Search CV. We need to set this as “RS”.feature_reduction: We will set this as true so that it will take into consideration the most important predictor variable for model creation.scoring_parameter: You can give your own parameter for scoring or otherwise it will assume appropriate according to the model. We will use “Weighted-f1” here.KMeans_featurizer: This should be true for linear and False for XGboost or random classifier because it can lead to overfitting.boosting_flag: Used for boosting. Here we will keep it as False.binning_flag: By default, it is False and can be set to True when we want to convert the top numeric variables into binned variables.add_poly: We will set it as false.stacking_flag: By default it is False. If set to True, it will add an additional feature which is derived from predictions of another model. We will keep it as False.Imbalanced_flag: It will check data imbalance if set to TRUE and will remove data imbalance using SMOTING technique.Verbose: Generally used to print the steps that are performed. We will set it as 3. train: It should contain the location of your dataset or if you have loaded it in a dataframe then the name of the dataframe. In this article we have loaded it in a dataframe named ‘df’ so we will set is as ‘df’. target: It contains the name of the target variable. In our case, the target variable name is “TenYearCHD”. test: It contains the test dataset. We can also leave it blank like this “” if we do not have any test dataset so that it will split the train dataset int train and test. sample_submission: We will leave it empty so that it will automatically create submission in our local directory. hyper_param: We will randomized search cv because it is 3X faster than Grid Search CV. We need to set this as “RS”. feature_reduction: We will set this as true so that it will take into consideration the most important predictor variable for model creation. scoring_parameter: You can give your own parameter for scoring or otherwise it will assume appropriate according to the model. We will use “Weighted-f1” here. KMeans_featurizer: This should be true for linear and False for XGboost or random classifier because it can lead to overfitting. boosting_flag: Used for boosting. Here we will keep it as False. binning_flag: By default, it is False and can be set to True when we want to convert the top numeric variables into binned variables. add_poly: We will set it as false. stacking_flag: By default it is False. If set to True, it will add an additional feature which is derived from predictions of another model. We will keep it as False. Imbalanced_flag: It will check data imbalance if set to TRUE and will remove data imbalance using SMOTING technique. Verbose: Generally used to print the steps that are performed. We will set it as 3. Now let us use all these parameters for our dataset and create the best performing model with the highest accuracy using AutoVIML. model, features, trainm, testm = Auto_ViML( train=df, target="TenYearCHD", test="", sample_submission="", hyper_param="RS", feature_reduction=True, scoring_parameter="weighted-f1", KMeans_Featurizer=False, Boosting_Flag=True, Binning_Flag=False, Add_Poly=False, Stacking_Flag=True, Imbalanced_Flag=True, verbose=3) Let us analyze the output we got. Data Analysis Part Data Analysis Part 2. Data Cleaning and Feature Selection 3. Data Balancing and Model Creation 4. Classification Report and Confusion Matrix 5. Model Visualizations 6. Feature Importance and Predictive Probability In the above set, we saw how AutoVIML handles the data, clean it, balance the outcome variable, and create the best model along with visualizations to get a better understanding. Similarly, you can explore AutoVIML using different datasets and share your experiences in the responses to this article. AutoVIML is an easy way to create best performing Machine Learning models according to your dataset. Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorial. Also, feel free to explore my profile and read different articles I have written related to Data Science.
[ { "code": null, "e": 484, "s": 172, "text": "Machine Learning provides the advantage of studying algorithms which improves automatically with experience. There are ’n’ numbers of machine learning algorithms and techniques and generally, we need to test most of them in order to find the best prediction model for our dataset which has the highest accuracy." }, { "code": null, "e": 910, "s": 484, "text": "Most of the machine learning methods like regression techniques, classification techniques, and other models are defined in Sklearn but in order to select which technique is best for our problem statement or our dataset, we need to try out all these models along with hyperparameter tuning and find out the best performing model. This takes a lot of time and effort which can be reduced using a python package named AutoVIML." }, { "code": null, "e": 1409, "s": 910, "text": "AutoVIML is an open-source python package that makes machine learning easy. What it does is, it renders your data through different machine learning models and finds out the best model with the highest accuracy for a given dataset. There is no need to preprocess the dataset to pass it to AutoVIML it automatically cleans your data, helps you in classifying the variables, performs feature reduction, can handle data with different types of variables like text, number, date, etc in a single model." }, { "code": null, "e": 1660, "s": 1409, "text": "In this article, we will see how we can use AutoVIML in order to reduce the time and effort we put to create machine learning models. We will see what are the different parameters which we use in AutoVIML and what changes they have on our prediction." }, { "code": null, "e": 1728, "s": 1660, "text": "Like any other python library, we will use pip to install autoviml." }, { "code": null, "e": 1749, "s": 1728, "text": "pip install autoviml" }, { "code": null, "e": 1790, "s": 1749, "text": "from autoviml.Auto_ViML import Auto_ViML" }, { "code": null, "e": 1997, "s": 1790, "text": "For exploring AutoVIML you can use any dataset, here I am going to use a Heart Disease-related dataset which you can download from Kaggle. This dataset contains different attributes and the target variable." }, { "code": null, "e": 2050, "s": 1997, "text": "import pandas as pddf = pd.read_csv('heart_d.csv')df" }, { "code": null, "e": 2181, "s": 2050, "text": "Now let us understand how we use autoviml to make a prediction model using this dataset and what parameters are there in AutoVIML." }, { "code": null, "e": 2554, "s": 2181, "text": "#Basic Example with all parametersmodel, features, trainm, testm = Auto_ViML( train, target, test, sample_submission, hyper_param=\"GS\", feature_reduction=True, scoring_parameter=\"weighted-f1\", KMeans_Featurizer=False, Boosting_Flag=False, Binning_Flag=False, Add_Poly=False, Stacking_Flag=False, Imbalanced_Flag=False, verbose=0,)" }, { "code": null, "e": 2727, "s": 2554, "text": "In the code above we can clearly see how to create the model using AutoVIML and what are the parameters, we can use. Now let us discuss what are these parameters in detail." }, { "code": null, "e": 4468, "s": 2727, "text": "train: It should contain the location of your dataset or if you have loaded it in a dataframe then the name of the dataframe. In this article we have loaded it in a dataframe named ‘df’ so we will set is as ‘df’.target: It contains the name of the target variable. In our case, the target variable name is “TenYearCHD”.test: It contains the test dataset. We can also leave it blank like this “” if we do not have any test dataset so that it will split the train dataset int train and test.sample_submission: We will leave it empty so that it will automatically create submission in our local directory.hyper_param: We will randomized search cv because it is 3X faster than Grid Search CV. We need to set this as “RS”.feature_reduction: We will set this as true so that it will take into consideration the most important predictor variable for model creation.scoring_parameter: You can give your own parameter for scoring or otherwise it will assume appropriate according to the model. We will use “Weighted-f1” here.KMeans_featurizer: This should be true for linear and False for XGboost or random classifier because it can lead to overfitting.boosting_flag: Used for boosting. Here we will keep it as False.binning_flag: By default, it is False and can be set to True when we want to convert the top numeric variables into binned variables.add_poly: We will set it as false.stacking_flag: By default it is False. If set to True, it will add an additional feature which is derived from predictions of another model. We will keep it as False.Imbalanced_flag: It will check data imbalance if set to TRUE and will remove data imbalance using SMOTING technique.Verbose: Generally used to print the steps that are performed. We will set it as 3." }, { "code": null, "e": 4681, "s": 4468, "text": "train: It should contain the location of your dataset or if you have loaded it in a dataframe then the name of the dataframe. In this article we have loaded it in a dataframe named ‘df’ so we will set is as ‘df’." }, { "code": null, "e": 4789, "s": 4681, "text": "target: It contains the name of the target variable. In our case, the target variable name is “TenYearCHD”." }, { "code": null, "e": 4960, "s": 4789, "text": "test: It contains the test dataset. We can also leave it blank like this “” if we do not have any test dataset so that it will split the train dataset int train and test." }, { "code": null, "e": 5074, "s": 4960, "text": "sample_submission: We will leave it empty so that it will automatically create submission in our local directory." }, { "code": null, "e": 5190, "s": 5074, "text": "hyper_param: We will randomized search cv because it is 3X faster than Grid Search CV. We need to set this as “RS”." }, { "code": null, "e": 5332, "s": 5190, "text": "feature_reduction: We will set this as true so that it will take into consideration the most important predictor variable for model creation." }, { "code": null, "e": 5491, "s": 5332, "text": "scoring_parameter: You can give your own parameter for scoring or otherwise it will assume appropriate according to the model. We will use “Weighted-f1” here." }, { "code": null, "e": 5620, "s": 5491, "text": "KMeans_featurizer: This should be true for linear and False for XGboost or random classifier because it can lead to overfitting." }, { "code": null, "e": 5685, "s": 5620, "text": "boosting_flag: Used for boosting. Here we will keep it as False." }, { "code": null, "e": 5819, "s": 5685, "text": "binning_flag: By default, it is False and can be set to True when we want to convert the top numeric variables into binned variables." }, { "code": null, "e": 5854, "s": 5819, "text": "add_poly: We will set it as false." }, { "code": null, "e": 6021, "s": 5854, "text": "stacking_flag: By default it is False. If set to True, it will add an additional feature which is derived from predictions of another model. We will keep it as False." }, { "code": null, "e": 6138, "s": 6021, "text": "Imbalanced_flag: It will check data imbalance if set to TRUE and will remove data imbalance using SMOTING technique." }, { "code": null, "e": 6222, "s": 6138, "text": "Verbose: Generally used to print the steps that are performed. We will set it as 3." }, { "code": null, "e": 6353, "s": 6222, "text": "Now let us use all these parameters for our dataset and create the best performing model with the highest accuracy using AutoVIML." }, { "code": null, "e": 6710, "s": 6353, "text": "model, features, trainm, testm = Auto_ViML( train=df, target=\"TenYearCHD\", test=\"\", sample_submission=\"\", hyper_param=\"RS\", feature_reduction=True, scoring_parameter=\"weighted-f1\", KMeans_Featurizer=False, Boosting_Flag=True, Binning_Flag=False, Add_Poly=False, Stacking_Flag=True, Imbalanced_Flag=True, verbose=3)" }, { "code": null, "e": 6744, "s": 6710, "text": "Let us analyze the output we got." }, { "code": null, "e": 6763, "s": 6744, "text": "Data Analysis Part" }, { "code": null, "e": 6782, "s": 6763, "text": "Data Analysis Part" }, { "code": null, "e": 6821, "s": 6782, "text": "2. Data Cleaning and Feature Selection" }, { "code": null, "e": 6858, "s": 6821, "text": "3. Data Balancing and Model Creation" }, { "code": null, "e": 6904, "s": 6858, "text": "4. Classification Report and Confusion Matrix" }, { "code": null, "e": 6928, "s": 6904, "text": "5. Model Visualizations" }, { "code": null, "e": 6977, "s": 6928, "text": "6. Feature Importance and Predictive Probability" }, { "code": null, "e": 7156, "s": 6977, "text": "In the above set, we saw how AutoVIML handles the data, clean it, balance the outcome variable, and create the best model along with visualizations to get a better understanding." }, { "code": null, "e": 7379, "s": 7156, "text": "Similarly, you can explore AutoVIML using different datasets and share your experiences in the responses to this article. AutoVIML is an easy way to create best performing Machine Learning models according to your dataset." } ]
JavaScript if else else if
Conditional statements are used to perform different actions based on different conditions. Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed The switch statement is described in the next chapter. Use the if statement to specify a block of JavaScript code to be executed if a condition is true. Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. Make a "Good day" greeting if the hour is less than 18:00: The result of greeting will be: Use the else statement to specify a block of code to be executed if the condition is false. If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening": The result of greeting will be: Use the else if statement to specify a new condition if the first condition is false. If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening": The result of greeting will be: Random link This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links. Fix the if statement to alert "Hello World" if x is greater than y. if x > y alert("Hello World"); Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 92, "s": 0, "text": "Conditional statements are used to perform different actions based on different conditions." }, { "code": null, "e": 187, "s": 92, "text": "Very often when you write code, you want to perform different actions for different decisions." }, { "code": null, "e": 247, "s": 187, "text": "You can use conditional statements in your code to do this." }, { "code": null, "e": 307, "s": 247, "text": "In JavaScript we have the following conditional statements:" }, { "code": null, "e": 390, "s": 307, "text": "Use if to specify a block of code to be executed, if a specified condition is true" }, { "code": null, "e": 476, "s": 390, "text": "Use else to specify a block of code to be executed, if the same condition is \n false" }, { "code": null, "e": 556, "s": 476, "text": "Use else if to specify a new condition to test, if the first condition is false" }, { "code": null, "e": 625, "s": 556, "text": "Use switch to specify many alternative blocks of code to be executed" }, { "code": null, "e": 680, "s": 625, "text": "The switch statement is described in the next chapter." }, { "code": null, "e": 779, "s": 680, "text": "Use the if statement to specify a block of JavaScript code to \nbe executed if a condition is true." }, { "code": null, "e": 880, "s": 779, "text": "Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error." }, { "code": null, "e": 940, "s": 880, "text": "Make a \"Good day\" greeting if the hour is less than \n18:00:" }, { "code": null, "e": 972, "s": 940, "text": "The result of greeting will be:" }, { "code": null, "e": 1066, "s": 972, "text": "Use the else statement to specify a block of code to be \nexecuted if the condition is \nfalse." }, { "code": null, "e": 1152, "s": 1066, "text": "If the hour is less than 18, create a \"Good day\" \ngreeting, otherwise \"Good evening\":" }, { "code": null, "e": 1184, "s": 1152, "text": "The result of greeting will be:" }, { "code": null, "e": 1270, "s": 1184, "text": "Use the else if statement to specify a new condition if the first condition is false." }, { "code": null, "e": 1430, "s": 1270, "text": "If time is less than 10:00, create a \"Good \nmorning\" \ngreeting, if not, but time is less than 20:00, create a \"Good day\" greeting, \notherwise a \"Good evening\":" }, { "code": null, "e": 1462, "s": 1430, "text": "The result of greeting will be:" }, { "code": null, "e": 1641, "s": 1462, "text": "Random link\nThis example will write a link to either W3Schools or to the World Wildlife \nFoundation (WWF). By using a random number, there is a 50% chance for each of the \nlinks." }, { "code": null, "e": 1709, "s": 1641, "text": "Fix the if statement to alert \"Hello World\" if x is greater than y." }, { "code": null, "e": 1745, "s": 1709, "text": "if x > y \n alert(\"Hello World\");\n\n" }, { "code": null, "e": 1764, "s": 1745, "text": "Start the Exercise" }, { "code": null, "e": 1797, "s": 1764, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1839, "s": 1797, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1946, "s": 1839, "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": 1965, "s": 1946, "text": "[email protected]" } ]
Pure CSS Menus - GeeksforGeeks
18 Oct, 2021 Menus are the main tools for visitors to navigate throughout a website. Pure.CSS comes up with very simple vertical and horizontal menus that can be easily customized by the developer. Pure CSS Menu Classes: Vertical Menu Horizontal Menu Selected and Disabled Items Inside a Menu Dropdown Menu Vertical Menu With Nested Submenu Vertical Menu: The Menus provided by Pure.CSS are vertical by default. The default styling is minimal so that the developer can customize it easily. The default vertical menu generally contains the full width of its container but the developer can specify it. The developer can also set the display attribute accordingly. pure-menu is the default class that generates the horizontal menu. It can contain the menu items and headings in the form of a list. pure-menu-list is the class for the unordered list that contains the menu items. The list items inside this list must have the class ‘pure-menu-item’. pure-menu-link is the class that is added to the links inside the menu items. pure-menu-heading is the class that is added for the headings inside or outside the menu list. By default, it capitalizes the text inside. Syntax : <div class="pure-menu"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> Some Text Here </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Some Text Here </a> </li> </ul> </div> Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Pure CSS Menus</title> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <style> .custom-width { display: inline-block; } .pure-menu-heading{ color: #308d46; } </style></head> <body> <div class="pure-menu custom-width"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> GeeksforGeeks </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Tutorials </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Students </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Jobs </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Courses </a> </li> </ul> </div></body> </html> Output: Horizontal Menu: Add the class ‘pure-menu-horizontal’ to the default vertical ‘pure-menu’ to make it a horizontal menu. The child elements like the pure-menu-list , pure-menu-item , pure-menu-link, and pure-menu-heading remain the same as the default vertical menu. Syntax: <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-heading">Some Text Here</li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Some Text Here </a> </li> </ul> </div> Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Pure CSS Menus</title> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <style> .pure-menu-heading{ color: #308d46; } </style></head> <body> <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> GeeksforGeeks </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Tutorials </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Students </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Jobs </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Courses </a> </li> </ul> </div></body> </html> Output: Selected and Disabled Items Inside the Menu: Pure CSS provides default classes that enable us to highlight a menu item as disabled or selected. ‘pure-menu-disabled‘ class name is added after the ‘pure-menu-item‘ to disable an item and the ‘pure-menu-selected‘ class name is added to make the item look like selected. Syntax: <li class="pure-menu-item pure-menu-disabled"> Inner Elements </li> <li class="pure-menu-item pure-menu-selected"> Inner Elements </li> Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Pure.CSS | Menus</title> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <style> .pure-menu-heading { color: #308d46; } </style></head> <body> <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> GeeksforGeeks </li> <li class="pure-menu-item pure-menu-selected"> <a href="#" class="pure-menu-link"> Selected </a> </li> <li class="pure-menu-item pure-menu-disabled"> <a href="#" class="pure-menu-link"> Disabled </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Normal </a> </li> </ul> </div></body> </html> Output: Dropdown Menu: Dropdown items can only be added to the horizontal menu. The steps to create a dropdown menu are discussed below. Pick the list item to which you want to add dropdown items and add the class ‘pure-menu-has-children‘ to it. Create an unordered list inside that element with a class of ‘pure-menu-children‘. Add the list items inside it with a class of ‘pure-menu-item‘. Add the class ‘pure-menu-allow-hover‘ to the parent list-item to make the dropdown occur on hover. Syntax: <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> Some Inner Elements <ul class="pure-menu-children"> <li class="pure-menu-item"> Inner Elements </li> </ul> </li> Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Pure.CSS | Menus</title> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <style> .pure-menu-heading { color: #308d46; } </style></head> <body> <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> GeeksforGeeks </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link"> Tutorials </a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Data Structures and Algorithms </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> GATE 2021 </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Practice </a> </li> </ul> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Students </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Jobs </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Courses </a> </li> </ul> </div></body> </html> Output: Vertical Menu With Nested Submenu: The method of creating a vertical menu with a nested submenu is very much similar to that of the dropdown menu. Just the menu has to be a default vertical menu instead of a horizontal menu. Syntax: <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> Some Inner Elements <ul class="pure-menu-children"> <li class="pure-menu-item"> Inner Elements </li> </ul> </li> Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Pure CSS Menus</title> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css"> <style> .pure-menu-heading { color: #308d46; } .custom-display { display: inline-block; } </style></head> <body> <div class="pure-menu custom-display"> <ul class="pure-menu-list"> <li class="pure-menu-heading"> GeeksforGeeks </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link"> Tutorials </a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Data Structures and Algorithms </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> GATE 2021 </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Practice </a> </li> </ul> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Students </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Jobs </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Courses </a> </li> </ul> </div></body> </html> Output: CSS-Questions Picked Pure CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24985, "s": 24957, "text": "\n18 Oct, 2021" }, { "code": null, "e": 25170, "s": 24985, "text": "Menus are the main tools for visitors to navigate throughout a website. Pure.CSS comes up with very simple vertical and horizontal menus that can be easily customized by the developer." }, { "code": null, "e": 25193, "s": 25170, "text": "Pure CSS Menu Classes:" }, { "code": null, "e": 25207, "s": 25193, "text": "Vertical Menu" }, { "code": null, "e": 25223, "s": 25207, "text": "Horizontal Menu" }, { "code": null, "e": 25265, "s": 25223, "text": "Selected and Disabled Items Inside a Menu" }, { "code": null, "e": 25279, "s": 25265, "text": "Dropdown Menu" }, { "code": null, "e": 25313, "s": 25279, "text": "Vertical Menu With Nested Submenu" }, { "code": null, "e": 25635, "s": 25313, "text": "Vertical Menu: The Menus provided by Pure.CSS are vertical by default. The default styling is minimal so that the developer can customize it easily. The default vertical menu generally contains the full width of its container but the developer can specify it. The developer can also set the display attribute accordingly." }, { "code": null, "e": 25769, "s": 25635, "text": "pure-menu is the default class that generates the horizontal menu. It can contain the menu items and headings in the form of a list." }, { "code": null, "e": 25921, "s": 25769, "text": "pure-menu-list is the class for the unordered list that contains the menu items. The list items inside this list must have the class ‘pure-menu-item’." }, { "code": null, "e": 25999, "s": 25921, "text": "pure-menu-link is the class that is added to the links inside the menu items." }, { "code": null, "e": 26138, "s": 25999, "text": "pure-menu-heading is the class that is added for the headings inside or outside the menu list. By default, it capitalizes the text inside." }, { "code": null, "e": 26148, "s": 26138, "text": "Syntax : " }, { "code": null, "e": 26447, "s": 26148, "text": "<div class=\"pure-menu\">\n <ul class=\"pure-menu-list\">\n <li class=\"pure-menu-heading\">\n Some Text Here\n </li>\n <li class=\"pure-menu-item\">\n <a href=\"#\" class=\"pure-menu-link\">\n Some Text Here\n </a>\n </li>\n </ul>\n</div>" }, { "code": null, "e": 26458, "s": 26449, "text": "Example:" }, { "code": null, "e": 26463, "s": 26458, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Pure CSS Menus</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\"> <style> .custom-width { display: inline-block; } .pure-menu-heading{ color: #308d46; } </style></head> <body> <div class=\"pure-menu custom-width\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-heading\"> GeeksforGeeks </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorials </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Students </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Jobs </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Courses </a> </li> </ul> </div></body> </html>", "e": 27613, "s": 26463, "text": null }, { "code": null, "e": 27621, "s": 27613, "text": "Output:" }, { "code": null, "e": 27887, "s": 27621, "text": "Horizontal Menu: Add the class ‘pure-menu-horizontal’ to the default vertical ‘pure-menu’ to make it a horizontal menu. The child elements like the pure-menu-list , pure-menu-item , pure-menu-link, and pure-menu-heading remain the same as the default vertical menu." }, { "code": null, "e": 27895, "s": 27887, "text": "Syntax:" }, { "code": null, "e": 28193, "s": 27895, "text": "<div class=\"pure-menu pure-menu-horizontal\">\n <ul class=\"pure-menu-list\">\n <li class=\"pure-menu-heading\">Some Text Here</li>\n <li class=\"pure-menu-item\">\n <a href=\"#\" class=\"pure-menu-link\">\n Some Text Here\n </a>\n </li>\n </ul>\n</div>" }, { "code": null, "e": 28203, "s": 28193, "text": "Example: " }, { "code": null, "e": 28208, "s": 28203, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Pure CSS Menus</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\"> <style> .pure-menu-heading{ color: #308d46; } </style></head> <body> <div class=\"pure-menu pure-menu-horizontal\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-heading\"> GeeksforGeeks </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorials </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Students </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Jobs </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Courses </a> </li> </ul> </div></body> </html>", "e": 29302, "s": 28208, "text": null }, { "code": null, "e": 29310, "s": 29302, "text": "Output:" }, { "code": null, "e": 29627, "s": 29310, "text": "Selected and Disabled Items Inside the Menu: Pure CSS provides default classes that enable us to highlight a menu item as disabled or selected. ‘pure-menu-disabled‘ class name is added after the ‘pure-menu-item‘ to disable an item and the ‘pure-menu-selected‘ class name is added to make the item look like selected." }, { "code": null, "e": 29635, "s": 29627, "text": "Syntax:" }, { "code": null, "e": 29779, "s": 29635, "text": "<li class=\"pure-menu-item pure-menu-disabled\">\n Inner Elements\n</li>\n<li class=\"pure-menu-item pure-menu-selected\">\n Inner Elements\n</li>" }, { "code": null, "e": 29788, "s": 29779, "text": "Example:" }, { "code": null, "e": 29793, "s": 29788, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Pure.CSS | Menus</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\"> <style> .pure-menu-heading { color: #308d46; } </style></head> <body> <div class=\"pure-menu pure-menu-horizontal\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-heading\"> GeeksforGeeks </li> <li class=\"pure-menu-item pure-menu-selected\"> <a href=\"#\" class=\"pure-menu-link\"> Selected </a> </li> <li class=\"pure-menu-item pure-menu-disabled\"> <a href=\"#\" class=\"pure-menu-link\"> Disabled </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Normal </a> </li> </ul> </div></body> </html>", "e": 30768, "s": 29793, "text": null }, { "code": null, "e": 30776, "s": 30768, "text": "Output:" }, { "code": null, "e": 30905, "s": 30776, "text": "Dropdown Menu: Dropdown items can only be added to the horizontal menu. The steps to create a dropdown menu are discussed below." }, { "code": null, "e": 31014, "s": 30905, "text": "Pick the list item to which you want to add dropdown items and add the class ‘pure-menu-has-children‘ to it." }, { "code": null, "e": 31097, "s": 31014, "text": "Create an unordered list inside that element with a class of ‘pure-menu-children‘." }, { "code": null, "e": 31160, "s": 31097, "text": "Add the list items inside it with a class of ‘pure-menu-item‘." }, { "code": null, "e": 31259, "s": 31160, "text": "Add the class ‘pure-menu-allow-hover‘ to the parent list-item to make the dropdown occur on hover." }, { "code": null, "e": 31267, "s": 31259, "text": "Syntax:" }, { "code": null, "e": 31498, "s": 31267, "text": "<li class=\"pure-menu-item \n pure-menu-has-children pure-menu-allow-hover\">\n Some Inner Elements\n <ul class=\"pure-menu-children\">\n <li class=\"pure-menu-item\">\n Inner Elements\n </li>\n </ul>\n</li>" }, { "code": null, "e": 31507, "s": 31498, "text": "Example:" }, { "code": null, "e": 31512, "s": 31507, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Pure.CSS | Menus</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\"> <style> .pure-menu-heading { color: #308d46; } </style></head> <body> <div class=\"pure-menu pure-menu-horizontal\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-heading\"> GeeksforGeeks </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorials </a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Data Structures and Algorithms </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> GATE 2021 </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Practice </a> </li> </ul> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Students </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Jobs </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Courses </a> </li> </ul> </div></body> </html>", "e": 33369, "s": 31512, "text": null }, { "code": null, "e": 33377, "s": 33369, "text": "Output:" }, { "code": null, "e": 33602, "s": 33377, "text": "Vertical Menu With Nested Submenu: The method of creating a vertical menu with a nested submenu is very much similar to that of the dropdown menu. Just the menu has to be a default vertical menu instead of a horizontal menu." }, { "code": null, "e": 33610, "s": 33602, "text": "Syntax:" }, { "code": null, "e": 33836, "s": 33610, "text": "<li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\">\n Some Inner Elements\n <ul class=\"pure-menu-children\">\n <li class=\"pure-menu-item\">\n Inner Elements\n </li>\n </ul>\n</li>" }, { "code": null, "e": 33845, "s": 33836, "text": "Example:" }, { "code": null, "e": 33850, "s": 33845, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Pure CSS Menus</title> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\"> <style> .pure-menu-heading { color: #308d46; } .custom-display { display: inline-block; } </style></head> <body> <div class=\"pure-menu custom-display\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-heading\"> GeeksforGeeks </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorials </a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Data Structures and Algorithms </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> GATE 2021 </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Practice </a> </li> </ul> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Students </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Jobs </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Courses </a> </li> </ul> </div></body> </html>", "e": 35769, "s": 33850, "text": null }, { "code": null, "e": 35777, "s": 35769, "text": "Output:" }, { "code": null, "e": 35791, "s": 35777, "text": "CSS-Questions" }, { "code": null, "e": 35798, "s": 35791, "text": "Picked" }, { "code": null, "e": 35807, "s": 35798, "text": "Pure CSS" }, { "code": null, "e": 35811, "s": 35807, "text": "CSS" }, { "code": null, "e": 35828, "s": 35811, "text": "Web Technologies" }, { "code": null, "e": 35926, "s": 35828, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35935, "s": 35926, "text": "Comments" }, { "code": null, "e": 35948, "s": 35935, "text": "Old Comments" }, { "code": null, "e": 35985, "s": 35948, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 36014, "s": 35985, "text": "Form validation using jQuery" }, { "code": null, "e": 36053, "s": 36014, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 36095, "s": 36053, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 36130, "s": 36095, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 36186, "s": 36130, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 36219, "s": 36186, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36262, "s": 36219, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36323, "s": 36262, "text": "Difference between var, let and const keywords in JavaScript" } ]
Count number of lines in a text file in Python
08 Jul, 2022 Prerequisites: File Handling in Python Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or an A loop approach. If you have a lot of files to work with To determine line count, use the Generator and Raw interface, If you don’t want to load the complete file in, utilize a loop and enumerate() for huge files. This program in Data file handling in Python emphasizes counting the number of lines in a text file in Python. Below is the implementation. Let’s suppose the text file looks like this – myfile.txt The readlines() are used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files Python3 with open(r"myfile.txt", 'r') as fp: lines = len(fp.readlines()) print('Total Number of lines:', lines) Output: Total Number of lines: 5 Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. Python3 with open(r"myfile.txt", 'r') as fp: for count, line in enumerate(fp): passprint('Total Number of lines:', count + 1) Output: Total Number of lines: 5 Loops python is used for sequential traversal. here we will count the number of lines using the loop and if statement. if help us to determine is there any character or not, if there will be any character present the IF condition returns true and the counter will increment. Python3 # Opening a filefile = open("gfg.txt", "r")Counter = 0 # Reading from fileContent = file.read()CoList = Content.split("\n") for i in CoList: if i: Counter += 1 print("This is the number of lines in the file")print(Counter) Output: This is the number of lines in the file 4 Loops python is used for sequential traversal. here we will count the number of lines using the sum function in Python. if help us to determine is there any character or not, if there will be any character present the IF condition returns true and the counter will increment. Python3 with open(r"myfile.txt", 'r') as fp: lines = sum(1 for line in fp) print('Total Number of lines:', lines) Output: Total Number of lines: 5 surajkumarguptaintern Python file-handling-programs python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 92, "s": 52, "text": "Prerequisites: File Handling in Python " }, { "code": null, "e": 660, "s": 92, "text": "Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or an A loop approach. If you have a lot of files to work with To determine line count, use the Generator and Raw interface, If you don’t want to load the complete file in, utilize a loop and enumerate() for huge files. This program in Data file handling in Python emphasizes counting the number of lines in a text file in Python. " }, { "code": null, "e": 690, "s": 660, "text": "Below is the implementation. " }, { "code": null, "e": 737, "s": 690, "text": "Let’s suppose the text file looks like this – " }, { "code": null, "e": 748, "s": 737, "text": "myfile.txt" }, { "code": null, "e": 914, "s": 748, "text": "The readlines() are used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files" }, { "code": null, "e": 922, "s": 914, "text": "Python3" }, { "code": "with open(r\"myfile.txt\", 'r') as fp: lines = len(fp.readlines()) print('Total Number of lines:', lines)", "e": 1032, "s": 922, "text": null }, { "code": null, "e": 1040, "s": 1032, "text": "Output:" }, { "code": null, "e": 1065, "s": 1040, "text": "Total Number of lines: 5" }, { "code": null, "e": 1163, "s": 1065, "text": "Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. " }, { "code": null, "e": 1171, "s": 1163, "text": "Python3" }, { "code": "with open(r\"myfile.txt\", 'r') as fp: for count, line in enumerate(fp): passprint('Total Number of lines:', count + 1)", "e": 1299, "s": 1171, "text": null }, { "code": null, "e": 1307, "s": 1299, "text": "Output:" }, { "code": null, "e": 1332, "s": 1307, "text": "Total Number of lines: 5" }, { "code": null, "e": 1607, "s": 1332, "text": "Loops python is used for sequential traversal. here we will count the number of lines using the loop and if statement. if help us to determine is there any character or not, if there will be any character present the IF condition returns true and the counter will increment." }, { "code": null, "e": 1615, "s": 1607, "text": "Python3" }, { "code": "# Opening a filefile = open(\"gfg.txt\", \"r\")Counter = 0 # Reading from fileContent = file.read()CoList = Content.split(\"\\n\") for i in CoList: if i: Counter += 1 print(\"This is the number of lines in the file\")print(Counter)", "e": 1848, "s": 1615, "text": null }, { "code": null, "e": 1856, "s": 1848, "text": "Output:" }, { "code": null, "e": 1898, "s": 1856, "text": "This is the number of lines in the file\n4" }, { "code": null, "e": 2174, "s": 1898, "text": "Loops python is used for sequential traversal. here we will count the number of lines using the sum function in Python. if help us to determine is there any character or not, if there will be any character present the IF condition returns true and the counter will increment." }, { "code": null, "e": 2182, "s": 2174, "text": "Python3" }, { "code": "with open(r\"myfile.txt\", 'r') as fp: lines = sum(1 for line in fp) print('Total Number of lines:', lines)", "e": 2294, "s": 2182, "text": null }, { "code": null, "e": 2302, "s": 2294, "text": "Output:" }, { "code": null, "e": 2327, "s": 2302, "text": "Total Number of lines: 5" }, { "code": null, "e": 2349, "s": 2327, "text": "surajkumarguptaintern" }, { "code": null, "e": 2379, "s": 2349, "text": "Python file-handling-programs" }, { "code": null, "e": 2400, "s": 2379, "text": "python-file-handling" }, { "code": null, "e": 2407, "s": 2400, "text": "Python" } ]
Angular CLI - ng version Command
This chapter explains the syntax, options of ng version command along with an example. The syntax for ng version command is as follows − ng version [options] ng v [options] ng version command shows the Angular CLI version installed. Options are optional parameters. An example for ng version command is given below − \>Node ng version _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 9.1.0 Node: 12.16.1 OS: win32 x64
[ { "code": null, "e": 2296, "s": 2209, "text": "This chapter explains the syntax, options of ng version command along with an example." }, { "code": null, "e": 2346, "s": 2296, "text": "The syntax for ng version command is as follows −" }, { "code": null, "e": 2383, "s": 2346, "text": "ng version [options]\nng v [options]\n" }, { "code": null, "e": 2443, "s": 2383, "text": "ng version command shows the Angular CLI version installed." }, { "code": null, "e": 2476, "s": 2443, "text": "Options are optional parameters." }, { "code": null, "e": 2527, "s": 2476, "text": "An example for ng version command is given below −" } ]
Random Pick with Weight in C++
Suppose we have an array w of positive integers, were w[i] describes the weight of index i, we have to define a function pickIndex() which randomly picks an index in proportion to its weight. So if the input is like [1,3], call pickIndex() five times, then the answer may come as − 0, 1, 1, 1, 0. To solve this, we will follow these steps − Define an array v, Through the initializer, initialize as n := w[0] for i in range 1 to size of ww[i] := w[i] + w[i – 1]n := w[i] w[i] := w[i] + w[i – 1] n := w[i] v = w The pickIndex() will work as follows − Take a random number r, perform r mod last element of v take the smallest number, not smaller than r from v, then subtract first number of v from the element and return. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int n; vector <int> v; Solution(vector<int>& w) { srand(time(NULL)); n = w[0]; for(int i = 1; i < w.size(); i++){ w[i] += w[i - 1]; n = w[i]; } v = w; } int pickIndex() { return upper_bound(v.begin(), v.end(), rand() % v.back()) - v.begin(); } }; main(){ vector<int> v = {1,3}; Solution ob(v); cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; cout << (ob.pickIndex()) << endl; } Initialize with [1, 3] and call pickIndex five times. 1 1 1 1 0
[ { "code": null, "e": 1379, "s": 1187, "text": "Suppose we have an array w of positive integers, were w[i] describes the weight of index i, we have to define a function pickIndex() which randomly picks an index in proportion to its weight." }, { "code": null, "e": 1484, "s": 1379, "text": "So if the input is like [1,3], call pickIndex() five times, then the answer may come as − 0, 1, 1, 1, 0." }, { "code": null, "e": 1528, "s": 1484, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1547, "s": 1528, "text": "Define an array v," }, { "code": null, "e": 1586, "s": 1547, "text": "Through the initializer, initialize as" }, { "code": null, "e": 1596, "s": 1586, "text": "n := w[0]" }, { "code": null, "e": 1658, "s": 1596, "text": "for i in range 1 to size of ww[i] := w[i] + w[i – 1]n := w[i]" }, { "code": null, "e": 1682, "s": 1658, "text": "w[i] := w[i] + w[i – 1]" }, { "code": null, "e": 1692, "s": 1682, "text": "n := w[i]" }, { "code": null, "e": 1698, "s": 1692, "text": "v = w" }, { "code": null, "e": 1737, "s": 1698, "text": "The pickIndex() will work as follows −" }, { "code": null, "e": 1793, "s": 1737, "text": "Take a random number r, perform r mod last element of v" }, { "code": null, "e": 1907, "s": 1793, "text": "take the smallest number, not smaller than r from v, then subtract first number of v from the element and return." }, { "code": null, "e": 1977, "s": 1907, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1988, "s": 1977, "text": " Live Demo" }, { "code": null, "e": 2621, "s": 1988, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int n;\n vector <int> v;\n Solution(vector<int>& w) {\n srand(time(NULL));\n n = w[0];\n for(int i = 1; i < w.size(); i++){\n w[i] += w[i - 1];\n n = w[i];\n }\n v = w;\n }\n int pickIndex() {\n return upper_bound(v.begin(), v.end(), rand() % v.back()) - v.begin();\n }\n};\nmain(){\n vector<int> v = {1,3};\n Solution ob(v);\n cout << (ob.pickIndex()) << endl;\n cout << (ob.pickIndex()) << endl;\n cout << (ob.pickIndex()) << endl;\n cout << (ob.pickIndex()) << endl;\n cout << (ob.pickIndex()) << endl;\n}" }, { "code": null, "e": 2675, "s": 2621, "text": "Initialize with [1, 3] and call pickIndex five times." }, { "code": null, "e": 2685, "s": 2675, "text": "1\n1\n1\n1\n0" } ]
Perl | Arrays
26 Nov, 2019 In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For", "Geeks"); Array Creation: In Perl programming every array variable is declared using “@” sign before the variable’s name. A single array can also store elements of multiple datatypes. For Example: # Define an array @arr = (1, 2, 3); @arr = (1, 2, 3, "Hello"); Array creation using qw function:qw() function is the easiest way to create an array of single-quoted words. It takes an expression as an input and extracts the words separated by a whitespace and then returns a list of those words. The best thing is that the expression can be surrounded by any delimiter like- () ” [] {} // etc. However () and // are used generally. Syntax: qw (Expression) qw /Expression/ qw 'Expression' qw {Expression} Example : # Perl program to demonstrate qw function # using qw function@arr1 = qw /This is a Perl Tutorial by GeeksforGeeks/; # Creates array2 with elements at# index 2,3,4 in array1@arr2 = @arr1[2,3,4]; print "Elements of arr1 are:\n";foreach $ele (@arr1){ print "$ele \n";} print "Elements of arr2 are:\n";foreach $ele (@arr2){ print "$ele \n";} Output: Elements of arr1 are: This is a Perl Tutorial by GeeksforGeeks Elements of arr2 are: a Perl Tutorial Accessing Array Elements: For accessing the elements of an array we must prefix “$” sign before the array variable name followed by the index in square brackets. For Example: # Define an array @arr = (1, 2, 3); # Accessing and printing first # element of an array print "$arr[0]\n"; # Accessing and printing second # element of an array print "$arr[1]\n"; Example: # Perl program to demonstrate Array's# creation and accessing the array's elements # Creation an array fruits@fruits = ("apple", "banana", "pineapple", "kiwi"); # printing the arrayprint "@fruits\n"; # Prints the array's elements# one by one using indexprint "$fruits[0]\n";print "$fruits[1]\n";print "$fruits[2]\n";print "$fruits[3]\n"; Output: apple banana pineapple kiwi apple banana pineapple kiwi Note: Array indices always start from zero. To access the first element it must to give 0 as indices. We can also give a negative index. But giving negative index will result in selecting the array elements from ending not from the beginning. Example: # Perl program to demonstrate # negative index of array # Creation an array fruits@fruits = ("apple", "banana", "pineapple", "kiwi"); # Prints the array's elements# one by one using negative indexprint "$fruits[-1]\n";print "$fruits[-2]\n"; Output: kiwi pineapple Sequential Number Arrays: Perl also provides a shortcut to make a sequential array of numbers or letters. It makes out the user’s task easy. Using sequential number arrays users can skip out loops and typing each element when counting to 1000 or letters A to Z etc. Example: @array = (1..9); # array with numbers from 1 to 9 @array = (a..h); # array with letters from a to h Program: # Perl program to demonstrate# Sequential Number Arrays # Sequential Number Arrays for # numbers and letters@nums = (1..9);@letters = (a..h); # Prints array- numsprint "@nums\n"; # Prints array- lettersprint "@letters\n"; Output: 1 2 3 4 5 6 7 8 9 a b c d e f g h Size of an Array: The size of an array(physical size of the array) can be found by evaluating the array in scalar context. The returned value will be the number of elements in the array. An array can be evaluated in scalar context using two ways: Implicit Scalar Context$size = @array;Explicit scalar context using keyword scalar$size = scalar @array; Implicit Scalar Context$size = @array; $size = @array; Explicit scalar context using keyword scalar$size = scalar @array; $size = scalar @array; Both ways will produce the same output so it is preferred to use an implicit scalar context. Example: # Perl program to demonstrate # the length of an array # declaring an array@arr = (11, 22, 33, 44, 55, 66); # Storing the length of array # in variable imp_size# implicit scalar context$imp_size = @arr; # Storing the length of array# in variable exp_size# explicit scalar context$exp_size = scalar @arr; print "Size of arr(imp_size) $imp_size\n";print "Size of arr(exp_size) $exp_size"; Output: Size of arr(imp_size) 6 Size of arr(exp_size) 6 Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e. size = maximum_index + 1 And you can find the maximum index of array by using $#array. So @array and scalar @array is always used to find the size of an array. Example: # Perl program to find size and # maximum index of an array #!/usr/bin/perl # Array declaration and # assigning values to it@arr = (10, 17, 19, 20, 25); # to find size of array$size_of_array = @arr; # to find Maximum index of array$maximum_index = $#arr; # displaying resultprint "Maximum Index of the Array: $maximum_index\n";print "The Size of the Array: $size_of_array\n"; Output: Maximum Index of the Array: 4 The Size of the Array: 5 Iterating through an Array: We can iterate in an array using two ways: Iterating through the range: We can iterate through the range by finding the size of an array and then running a for loop from 0 to the size – 1 and then accessing the elements of the array.Example:# Perl program to illustrate # iteration through range # array creation@arr = (11, 22, 33, 44, 55); # size of array$len = @arr; for ($b = 0; $b < $len; $b = $b + 1){ print "\@arr[$b] = $arr[$b]\n";}Output:@arr[0] = 11 @arr[1] = 22 @arr[2] = 33 @arr[3] = 44 @arr[4] = 55 Example: # Perl program to illustrate # iteration through range # array creation@arr = (11, 22, 33, 44, 55); # size of array$len = @arr; for ($b = 0; $b < $len; $b = $b + 1){ print "\@arr[$b] = $arr[$b]\n";} Output: @arr[0] = 11 @arr[1] = 22 @arr[2] = 33 @arr[3] = 44 @arr[4] = 55 Iterating through elements(foreach Loop): We can iterate through the elements using foreach loop. Using this we can directly access the elements of the array using a loop instead of running a loop over its range and then accessing the elements.Example:# Perl program to illustrate Iterating # through elements(foreach Loop) # creating array@l = (11, 22, 33, 44, 55); # foreach loopforeach $a (@l){ print "$a ";}Output:11 22 33 44 55 Example: # Perl program to illustrate Iterating # through elements(foreach Loop) # creating array@l = (11, 22, 33, 44, 55); # foreach loopforeach $a (@l){ print "$a ";} Output: 11 22 33 44 55 Akanksha_Rai ManasChhabra2 shubham_singh perl-basics Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Subroutines or Functions Use of print() and say() in Perl
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Nov, 2019" }, { "code": null, "e": 303, "s": 53, "text": "In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example:" }, { "code": null, "e": 377, "s": 303, "text": "@number = (50, 70, 46); \n@names = (\"Geeks\", \"For\", \"Geeks\");\n" }, { "code": null, "e": 564, "s": 377, "text": "Array Creation: In Perl programming every array variable is declared using “@” sign before the variable’s name. A single array can also store elements of multiple datatypes. For Example:" }, { "code": null, "e": 628, "s": 564, "text": "# Define an array\n@arr = (1, 2, 3);\n@arr = (1, 2, 3, \"Hello\");\n" }, { "code": null, "e": 997, "s": 628, "text": "Array creation using qw function:qw() function is the easiest way to create an array of single-quoted words. It takes an expression as an input and extracts the words separated by a whitespace and then returns a list of those words. The best thing is that the expression can be surrounded by any delimiter like- () ” [] {} // etc. However () and // are used generally." }, { "code": null, "e": 1005, "s": 997, "text": "Syntax:" }, { "code": null, "e": 1070, "s": 1005, "text": "qw (Expression)\nqw /Expression/\nqw 'Expression'\nqw {Expression}\n" }, { "code": null, "e": 1080, "s": 1070, "text": "Example :" }, { "code": "# Perl program to demonstrate qw function # using qw function@arr1 = qw /This is a Perl Tutorial by GeeksforGeeks/; # Creates array2 with elements at# index 2,3,4 in array1@arr2 = @arr1[2,3,4]; print \"Elements of arr1 are:\\n\";foreach $ele (@arr1){ print \"$ele \\n\";} print \"Elements of arr2 are:\\n\";foreach $ele (@arr2){ print \"$ele \\n\";}", "e": 1430, "s": 1080, "text": null }, { "code": null, "e": 1438, "s": 1430, "text": "Output:" }, { "code": null, "e": 1550, "s": 1438, "text": "Elements of arr1 are:\nThis \nis \na \nPerl \nTutorial \nby \nGeeksforGeeks \nElements of arr2 are:\na \nPerl \nTutorial \n" }, { "code": null, "e": 1725, "s": 1550, "text": "Accessing Array Elements: For accessing the elements of an array we must prefix “$” sign before the array variable name followed by the index in square brackets. For Example:" }, { "code": null, "e": 1910, "s": 1725, "text": "# Define an array\n@arr = (1, 2, 3);\n\n# Accessing and printing first \n# element of an array\nprint \"$arr[0]\\n\";\n\n# Accessing and printing second\n# element of an array\nprint \"$arr[1]\\n\";\n" }, { "code": null, "e": 1919, "s": 1910, "text": "Example:" }, { "code": "# Perl program to demonstrate Array's# creation and accessing the array's elements # Creation an array fruits@fruits = (\"apple\", \"banana\", \"pineapple\", \"kiwi\"); # printing the arrayprint \"@fruits\\n\"; # Prints the array's elements# one by one using indexprint \"$fruits[0]\\n\";print \"$fruits[1]\\n\";print \"$fruits[2]\\n\";print \"$fruits[3]\\n\";", "e": 2260, "s": 1919, "text": null }, { "code": null, "e": 2268, "s": 2260, "text": "Output:" }, { "code": null, "e": 2325, "s": 2268, "text": "apple banana pineapple kiwi\napple\nbanana\npineapple\nkiwi\n" }, { "code": null, "e": 2568, "s": 2325, "text": "Note: Array indices always start from zero. To access the first element it must to give 0 as indices. We can also give a negative index. But giving negative index will result in selecting the array elements from ending not from the beginning." }, { "code": null, "e": 2577, "s": 2568, "text": "Example:" }, { "code": "# Perl program to demonstrate # negative index of array # Creation an array fruits@fruits = (\"apple\", \"banana\", \"pineapple\", \"kiwi\"); # Prints the array's elements# one by one using negative indexprint \"$fruits[-1]\\n\";print \"$fruits[-2]\\n\";", "e": 2820, "s": 2577, "text": null }, { "code": null, "e": 2828, "s": 2820, "text": "Output:" }, { "code": null, "e": 2843, "s": 2828, "text": "kiwi\npineapple" }, { "code": null, "e": 3109, "s": 2843, "text": "Sequential Number Arrays: Perl also provides a shortcut to make a sequential array of numbers or letters. It makes out the user’s task easy. Using sequential number arrays users can skip out loops and typing each element when counting to 1000 or letters A to Z etc." }, { "code": null, "e": 3118, "s": 3109, "text": "Example:" }, { "code": null, "e": 3219, "s": 3118, "text": "@array = (1..9); # array with numbers from 1 to 9\n@array = (a..h); # array with letters from a to h\n" }, { "code": null, "e": 3228, "s": 3219, "text": "Program:" }, { "code": "# Perl program to demonstrate# Sequential Number Arrays # Sequential Number Arrays for # numbers and letters@nums = (1..9);@letters = (a..h); # Prints array- numsprint \"@nums\\n\"; # Prints array- lettersprint \"@letters\\n\"; ", "e": 3456, "s": 3228, "text": null }, { "code": null, "e": 3464, "s": 3456, "text": "Output:" }, { "code": null, "e": 3499, "s": 3464, "text": "1 2 3 4 5 6 7 8 9\na b c d e f g h\n" }, { "code": null, "e": 3746, "s": 3499, "text": "Size of an Array: The size of an array(physical size of the array) can be found by evaluating the array in scalar context. The returned value will be the number of elements in the array. An array can be evaluated in scalar context using two ways:" }, { "code": null, "e": 3851, "s": 3746, "text": "Implicit Scalar Context$size = @array;Explicit scalar context using keyword scalar$size = scalar @array;" }, { "code": null, "e": 3890, "s": 3851, "text": "Implicit Scalar Context$size = @array;" }, { "code": null, "e": 3906, "s": 3890, "text": "$size = @array;" }, { "code": null, "e": 3973, "s": 3906, "text": "Explicit scalar context using keyword scalar$size = scalar @array;" }, { "code": null, "e": 3996, "s": 3973, "text": "$size = scalar @array;" }, { "code": null, "e": 4089, "s": 3996, "text": "Both ways will produce the same output so it is preferred to use an implicit scalar context." }, { "code": null, "e": 4098, "s": 4089, "text": "Example:" }, { "code": "# Perl program to demonstrate # the length of an array # declaring an array@arr = (11, 22, 33, 44, 55, 66); # Storing the length of array # in variable imp_size# implicit scalar context$imp_size = @arr; # Storing the length of array# in variable exp_size# explicit scalar context$exp_size = scalar @arr; print \"Size of arr(imp_size) $imp_size\\n\";print \"Size of arr(exp_size) $exp_size\";", "e": 4489, "s": 4098, "text": null }, { "code": null, "e": 4497, "s": 4489, "text": "Output:" }, { "code": null, "e": 4546, "s": 4497, "text": "Size of arr(imp_size) 6\nSize of arr(exp_size) 6\n" }, { "code": null, "e": 4633, "s": 4546, "text": "Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e." }, { "code": null, "e": 4658, "s": 4633, "text": "size = maximum_index + 1" }, { "code": null, "e": 4793, "s": 4658, "text": "And you can find the maximum index of array by using $#array. So @array and scalar @array is always used to find the size of an array." }, { "code": null, "e": 4802, "s": 4793, "text": "Example:" }, { "code": "# Perl program to find size and # maximum index of an array #!/usr/bin/perl # Array declaration and # assigning values to it@arr = (10, 17, 19, 20, 25); # to find size of array$size_of_array = @arr; # to find Maximum index of array$maximum_index = $#arr; # displaying resultprint \"Maximum Index of the Array: $maximum_index\\n\";print \"The Size of the Array: $size_of_array\\n\";", "e": 5184, "s": 4802, "text": null }, { "code": null, "e": 5192, "s": 5184, "text": "Output:" }, { "code": null, "e": 5249, "s": 5192, "text": "Maximum Index of the Array: 4\nThe Size of the Array: 5\n" }, { "code": null, "e": 5320, "s": 5249, "text": "Iterating through an Array: We can iterate in an array using two ways:" }, { "code": null, "e": 5795, "s": 5320, "text": "Iterating through the range: We can iterate through the range by finding the size of an array and then running a for loop from 0 to the size – 1 and then accessing the elements of the array.Example:# Perl program to illustrate # iteration through range # array creation@arr = (11, 22, 33, 44, 55); # size of array$len = @arr; for ($b = 0; $b < $len; $b = $b + 1){ print \"\\@arr[$b] = $arr[$b]\\n\";}Output:@arr[0] = 11\n@arr[1] = 22\n@arr[2] = 33\n@arr[3] = 44\n@arr[4] = 55\n" }, { "code": null, "e": 5804, "s": 5795, "text": "Example:" }, { "code": "# Perl program to illustrate # iteration through range # array creation@arr = (11, 22, 33, 44, 55); # size of array$len = @arr; for ($b = 0; $b < $len; $b = $b + 1){ print \"\\@arr[$b] = $arr[$b]\\n\";}", "e": 6009, "s": 5804, "text": null }, { "code": null, "e": 6017, "s": 6009, "text": "Output:" }, { "code": null, "e": 6083, "s": 6017, "text": "@arr[0] = 11\n@arr[1] = 22\n@arr[2] = 33\n@arr[3] = 44\n@arr[4] = 55\n" }, { "code": null, "e": 6524, "s": 6083, "text": "Iterating through elements(foreach Loop): We can iterate through the elements using foreach loop. Using this we can directly access the elements of the array using a loop instead of running a loop over its range and then accessing the elements.Example:# Perl program to illustrate Iterating # through elements(foreach Loop) # creating array@l = (11, 22, 33, 44, 55); # foreach loopforeach $a (@l){ print \"$a \";}Output:11 22 33 44 55\n" }, { "code": null, "e": 6533, "s": 6524, "text": "Example:" }, { "code": "# Perl program to illustrate Iterating # through elements(foreach Loop) # creating array@l = (11, 22, 33, 44, 55); # foreach loopforeach $a (@l){ print \"$a \";}", "e": 6700, "s": 6533, "text": null }, { "code": null, "e": 6708, "s": 6700, "text": "Output:" }, { "code": null, "e": 6724, "s": 6708, "text": "11 22 33 44 55\n" }, { "code": null, "e": 6737, "s": 6724, "text": "Akanksha_Rai" }, { "code": null, "e": 6751, "s": 6737, "text": "ManasChhabra2" }, { "code": null, "e": 6765, "s": 6751, "text": "shubham_singh" }, { "code": null, "e": 6777, "s": 6765, "text": "perl-basics" }, { "code": null, "e": 6782, "s": 6777, "text": "Perl" }, { "code": null, "e": 6787, "s": 6782, "text": "Perl" }, { "code": null, "e": 6885, "s": 6787, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6909, "s": 6885, "text": "Perl | split() Function" }, { "code": null, "e": 6932, "s": 6909, "text": "Perl | push() Function" }, { "code": null, "e": 6956, "s": 6932, "text": "Perl | chomp() Function" }, { "code": null, "e": 6981, "s": 6956, "text": "Perl | substr() function" }, { "code": null, "e": 7004, "s": 6981, "text": "Perl | grep() Function" }, { "code": null, "e": 7029, "s": 7004, "text": "Perl | exists() Function" }, { "code": null, "e": 7070, "s": 7029, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 7095, "s": 7070, "text": "Perl | length() Function" }, { "code": null, "e": 7127, "s": 7095, "text": "Perl | Subroutines or Functions" } ]
PL/SQL - Triggers
In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events − A database manipulation (DML) statement (DELETE, INSERT, or UPDATE) A database manipulation (DML) statement (DELETE, INSERT, or UPDATE) A database definition (DDL) statement (CREATE, ALTER, or DROP). A database definition (DDL) statement (CREATE, ALTER, or DROP). A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Triggers can be defined on the table, view, schema, or database with which the event is associated. Triggers can be written for the following purposes − Generating some derived column values automatically Enforcing referential integrity Event logging and storing information on table access Auditing Synchronous replication of tables Imposing security authorizations Preventing invalid transactions The syntax for creating a trigger is − CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements BEGIN Executable-statements EXCEPTION Exception-handling-statements END; Where, CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name. CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name. {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view. {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view. {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation. {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation. [OF col_name] − This specifies the column name that will be updated. [OF col_name] − This specifies the column name that will be updated. [ON table_name] − This specifies the name of the table associated with the trigger. [ON table_name] − This specifies the name of the table associated with the trigger. [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE. [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE. [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers. WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers. To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters − Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+ The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values − CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE sal_diff number; BEGIN sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary difference: ' || sal_diff); END; / When the above code is executed at the SQL prompt, it produces the following result − Trigger created. The following points need to be considered here − OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers. OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers. If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state. If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state. The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table. The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table. Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table − INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result − Old salary: New salary: 7500 Salary difference: Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table − UPDATE customers SET salary = salary + 500 WHERE id = 2; When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result − Old salary: 1500 New salary: 2000 Salary difference: 500
[ { "code": null, "e": 2439, "s": 2199, "text": "In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −" }, { "code": null, "e": 2507, "s": 2439, "text": "A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)" }, { "code": null, "e": 2575, "s": 2507, "text": "A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)" }, { "code": null, "e": 2639, "s": 2575, "text": "A database definition (DDL) statement (CREATE, ALTER, or DROP)." }, { "code": null, "e": 2703, "s": 2639, "text": "A database definition (DDL) statement (CREATE, ALTER, or DROP)." }, { "code": null, "e": 2776, "s": 2703, "text": "A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)." }, { "code": null, "e": 2849, "s": 2776, "text": "A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)." }, { "code": null, "e": 2949, "s": 2849, "text": "Triggers can be defined on the table, view, schema, or database with which the event is associated." }, { "code": null, "e": 3002, "s": 2949, "text": "Triggers can be written for the following purposes −" }, { "code": null, "e": 3054, "s": 3002, "text": "Generating some derived column values automatically" }, { "code": null, "e": 3086, "s": 3054, "text": "Enforcing referential integrity" }, { "code": null, "e": 3140, "s": 3086, "text": "Event logging and storing information on table access" }, { "code": null, "e": 3149, "s": 3140, "text": "Auditing" }, { "code": null, "e": 3183, "s": 3149, "text": "Synchronous replication of tables" }, { "code": null, "e": 3216, "s": 3183, "text": "Imposing security authorizations" }, { "code": null, "e": 3248, "s": 3216, "text": "Preventing invalid transactions" }, { "code": null, "e": 3287, "s": 3248, "text": "The syntax for creating a trigger is −" }, { "code": null, "e": 3627, "s": 3287, "text": "CREATE [OR REPLACE ] TRIGGER trigger_name \n{BEFORE | AFTER | INSTEAD OF } \n{INSERT [OR] | UPDATE [OR] | DELETE} \n[OF col_name] \nON table_name \n[REFERENCING OLD AS o NEW AS n] \n[FOR EACH ROW] \nWHEN (condition) \nDECLARE \n Declaration-statements \nBEGIN \n Executable-statements \nEXCEPTION \n Exception-handling-statements \nEND; " }, { "code": null, "e": 3634, "s": 3627, "text": "Where," }, { "code": null, "e": 3740, "s": 3634, "text": "CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name." }, { "code": null, "e": 3846, "s": 3740, "text": "CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name." }, { "code": null, "e": 3990, "s": 3846, "text": "{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view." }, { "code": null, "e": 4134, "s": 3990, "text": "{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view." }, { "code": null, "e": 4207, "s": 4134, "text": "{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation." }, { "code": null, "e": 4280, "s": 4207, "text": "{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation." }, { "code": null, "e": 4349, "s": 4280, "text": "[OF col_name] − This specifies the column name that will be updated." }, { "code": null, "e": 4418, "s": 4349, "text": "[OF col_name] − This specifies the column name that will be updated." }, { "code": null, "e": 4502, "s": 4418, "text": "[ON table_name] − This specifies the name of the table associated with the trigger." }, { "code": null, "e": 4586, "s": 4502, "text": "[ON table_name] − This specifies the name of the table associated with the trigger." }, { "code": null, "e": 4728, "s": 4586, "text": "[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE." }, { "code": null, "e": 4870, "s": 4728, "text": "[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE." }, { "code": null, "e": 5107, "s": 4870, "text": "[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger." }, { "code": null, "e": 5344, "s": 5107, "text": "[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger." }, { "code": null, "e": 5482, "s": 5344, "text": "WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers." }, { "code": null, "e": 5620, "s": 5482, "text": "WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers." }, { "code": null, "e": 5723, "s": 5620, "text": "To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −" }, { "code": null, "e": 6232, "s": 5723, "text": "Select * from customers; \n\n+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 6486, "s": 6232, "text": "The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values −" }, { "code": null, "e": 6882, "s": 6486, "text": "CREATE OR REPLACE TRIGGER display_salary_changes \nBEFORE DELETE OR INSERT OR UPDATE ON customers \nFOR EACH ROW \nWHEN (NEW.ID > 0) \nDECLARE \n sal_diff number; \nBEGIN \n sal_diff := :NEW.salary - :OLD.salary; \n dbms_output.put_line('Old salary: ' || :OLD.salary); \n dbms_output.put_line('New salary: ' || :NEW.salary); \n dbms_output.put_line('Salary difference: ' || sal_diff); \nEND; \n/ " }, { "code": null, "e": 6968, "s": 6882, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 6986, "s": 6968, "text": "Trigger created.\n" }, { "code": null, "e": 7036, "s": 6986, "text": "The following points need to be considered here −" }, { "code": null, "e": 7154, "s": 7036, "text": "OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers." }, { "code": null, "e": 7272, "s": 7154, "text": "OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers." }, { "code": null, "e": 7507, "s": 7272, "text": "If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state." }, { "code": null, "e": 7742, "s": 7507, "text": "If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state." }, { "code": null, "e": 8056, "s": 7742, "text": "The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table." }, { "code": null, "e": 8370, "s": 8056, "text": "The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table." }, { "code": null, "e": 8505, "s": 8370, "text": "Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table −" }, { "code": null, "e": 8599, "s": 8505, "text": "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (7, 'Kriti', 22, 'HP', 7500.00 ); " }, { "code": null, "e": 8754, "s": 8599, "text": "When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −" }, { "code": null, "e": 8805, "s": 8754, "text": "Old salary: \nNew salary: 7500 \nSalary difference:\n" }, { "code": null, "e": 9032, "s": 8805, "text": "Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table −" }, { "code": null, "e": 9092, "s": 9032, "text": "UPDATE customers \nSET salary = salary + 500 \nWHERE id = 2; " }, { "code": null, "e": 9247, "s": 9092, "text": "When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −" } ]
Docker – Concept of Dockerfile
28 Jul, 2021 Dockerfile is a simple text file with instructions to build a Docker image. As shown below dockerfile is a simple text file where we give some instructions to build an image. And when we run docker build command a file image gets created. If you want to create your own image you can use a dockerfile. So dockerfile is basically automation of docker image creation and there are some basic instructions that you use in the docker file. Let’s check out how it’s done. Follow the below steps to create a dockerfile: Step 1: Create a file name called “Dockerfile”.By default when you run the docker build commands docker searches for a file named Dockerfile. However, it is not compulsory, you can also give some different names, and then you can tell the docker that this particular file is a local file but for now we will go with the Dockerfile. Step 2: The very first instruction that a dockerfile starts with is FROM. Here you have to give a base image. So for example, if you want to get a base image from ubuntu we will use FROM ubuntu. FROM ubuntu Then the other instruction is you have to give a MAINTAINER. This is optional but its best practice that you give the maintainer of this image so that it is very easy to find out who is the maintainer and you can give your name and email as well. And if you want you can just give the email as well without giving the name. But here we are giving the entire thing here. MAINTAINER YOUR_NAME <YOUR_EMAIL_ID> Next, we want to run something so we will say run any command we can use RUN and add the command that you need to run. RUN apt-get update . And if you want to run something on the command line during container creation you can give CMD and inside square brackets, we add the command. Here it ba as shown below: CMD ["echo", "Hello Geeks!"] At this point the file will have the following commands: FROM ubuntu MAINTAINER YOUR_NAME <YOUR_EMAIL_ID> RUN apt-get update CMD ["echo", "Hello Geeks!"] Step 3: Now we have to build the image so here are the commands you can use: docker build /<FILE_LOCATION> Or, docker build . -f Dockerfile.txt It says docker build and you have to give the location of your docker file. This will start building the image. Now if we use the below command, we can check if the docker image has been created: docker images So we have successfully created a Dockerfile and a respective Docker image for the same. docker Picked Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Docker - COPY Instruction ML | Monte Carlo Tree Search (MCTS) Markov Decision Process How to Run a Python Script using Docker? Copying Files to and from Docker Containers ML | Underfitting and Overfitting Basics of API Testing Using Postman Clustering in Machine Learning ML | Label Encoding of datasets in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 268, "s": 28, "text": "Dockerfile is a simple text file with instructions to build a Docker image. As shown below dockerfile is a simple text file where we give some instructions to build an image. And when we run docker build command a file image gets created." }, { "code": null, "e": 496, "s": 268, "text": "If you want to create your own image you can use a dockerfile. So dockerfile is basically automation of docker image creation and there are some basic instructions that you use in the docker file. Let’s check out how it’s done." }, { "code": null, "e": 543, "s": 496, "text": "Follow the below steps to create a dockerfile:" }, { "code": null, "e": 875, "s": 543, "text": "Step 1: Create a file name called “Dockerfile”.By default when you run the docker build commands docker searches for a file named Dockerfile. However, it is not compulsory, you can also give some different names, and then you can tell the docker that this particular file is a local file but for now we will go with the Dockerfile." }, { "code": null, "e": 1073, "s": 875, "text": "Step 2: The very first instruction that a dockerfile starts with is FROM. Here you have to give a base image. So for example, if you want to get a base image from ubuntu we will use FROM ubuntu. " }, { "code": null, "e": 1085, "s": 1073, "text": "FROM ubuntu" }, { "code": null, "e": 1456, "s": 1085, "text": "Then the other instruction is you have to give a MAINTAINER. This is optional but its best practice that you give the maintainer of this image so that it is very easy to find out who is the maintainer and you can give your name and email as well. And if you want you can just give the email as well without giving the name. But here we are giving the entire thing here. " }, { "code": null, "e": 1493, "s": 1456, "text": "MAINTAINER YOUR_NAME <YOUR_EMAIL_ID>" }, { "code": null, "e": 1612, "s": 1493, "text": "Next, we want to run something so we will say run any command we can use RUN and add the command that you need to run." }, { "code": null, "e": 1631, "s": 1612, "text": "RUN apt-get update" }, { "code": null, "e": 1804, "s": 1631, "text": ". And if you want to run something on the command line during container creation you can give CMD and inside square brackets, we add the command. Here it ba as shown below:" }, { "code": null, "e": 1833, "s": 1804, "text": "CMD [\"echo\", \"Hello Geeks!\"]" }, { "code": null, "e": 1890, "s": 1833, "text": "At this point the file will have the following commands:" }, { "code": null, "e": 1987, "s": 1890, "text": "FROM ubuntu\nMAINTAINER YOUR_NAME <YOUR_EMAIL_ID>\nRUN apt-get update\nCMD [\"echo\", \"Hello Geeks!\"]" }, { "code": null, "e": 2064, "s": 1987, "text": "Step 3: Now we have to build the image so here are the commands you can use:" }, { "code": null, "e": 2095, "s": 2064, "text": "docker build /<FILE_LOCATION> " }, { "code": null, "e": 2099, "s": 2095, "text": "Or," }, { "code": null, "e": 2132, "s": 2099, "text": "docker build . -f Dockerfile.txt" }, { "code": null, "e": 2245, "s": 2132, "text": "It says docker build and you have to give the location of your docker file. This will start building the image." }, { "code": null, "e": 2329, "s": 2245, "text": "Now if we use the below command, we can check if the docker image has been created:" }, { "code": null, "e": 2343, "s": 2329, "text": "docker images" }, { "code": null, "e": 2432, "s": 2343, "text": "So we have successfully created a Dockerfile and a respective Docker image for the same." }, { "code": null, "e": 2439, "s": 2432, "text": "docker" }, { "code": null, "e": 2446, "s": 2439, "text": "Picked" }, { "code": null, "e": 2472, "s": 2446, "text": "Advanced Computer Subject" }, { "code": null, "e": 2570, "s": 2472, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2593, "s": 2570, "text": "System Design Tutorial" }, { "code": null, "e": 2619, "s": 2593, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2655, "s": 2619, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2679, "s": 2655, "text": "Markov Decision Process" }, { "code": null, "e": 2720, "s": 2679, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 2764, "s": 2720, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 2798, "s": 2764, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 2834, "s": 2798, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 2865, "s": 2834, "text": "Clustering in Machine Learning" } ]
Python | os.sched_setaffinity() method
02 Nov, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.sched_setaffinity() method in Python is used to set the CPU affinity mask of a process indicated by the specified process id. A process’s CPU affinity mask determines the set of CPUs on which it is eligible to run. Note: This method is only available on some UNIX platforms. Syntax: os.sched_setaffinity(pid, mask) Parameter:pid: The process id of the process whose CPU affinity mask is to be set required. Process’s CPU affinity mask determines the set of CPUs on which it is eligible to run.A pid of 0 represents the calling process.mask: An iterable of integers representing the set of CPUs to which the process should be restricted. Return Type: This method does not return any value. # Python program to explain os.sched_setaffinity() method # importing os module import os # Get the number of CPUs# in the system# using os.cpu_count() methodprint("Number of CPUs:", os.cpu_count()) # Get the set of CPUs# on which the calling process# is eligible to run. using# os.sched_getaffinity() method# 0 as PID represents the# calling processpid = 0affinity = os.sched_getaffinity(pid) # Print the resultprint("Process is eligible to run on:", affinity) # Change the CPU affinity mask# of the calling process# using os.sched_setaffinity() method # Below CPU affinity mask will# restrict a process to only# these 2 CPUs (0, 1) i.e process can# run on these CPUs onlyaffinity_mask = {0, 1}pid = 0os.sched_setaffinity(0, affinity_mask)print("CPU affinity mask is modified for process id % s" % pid) # Now again, Get the set of CPUs# on which the calling process# is eligible to run.pid = 0affinity = os.sched_getaffinity(pid) # Print the resultprint("Now, process is eligible to run on:", affinity) Number of CPUs: 4 Process is eligible to run on: {0, 1, 2, 3} CPU affinity mask is modified for process id 0 Now, process is eligible to run on: {0, 1} References: https://docs.python.org/3/library/os.html#os.sched_setaffinity https://linux.die.net/man/2/sched_getaffinity adnanirshad158 clintra python-os-module 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": "\n02 Nov, 2021" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 465, "s": 247, "text": "os.sched_setaffinity() method in Python is used to set the CPU affinity mask of a process indicated by the specified process id. A process’s CPU affinity mask determines the set of CPUs on which it is eligible to run." }, { "code": null, "e": 525, "s": 465, "text": "Note: This method is only available on some UNIX platforms." }, { "code": null, "e": 565, "s": 525, "text": "Syntax: os.sched_setaffinity(pid, mask)" }, { "code": null, "e": 887, "s": 565, "text": "Parameter:pid: The process id of the process whose CPU affinity mask is to be set required. Process’s CPU affinity mask determines the set of CPUs on which it is eligible to run.A pid of 0 represents the calling process.mask: An iterable of integers representing the set of CPUs to which the process should be restricted." }, { "code": null, "e": 939, "s": 887, "text": "Return Type: This method does not return any value." }, { "code": "# Python program to explain os.sched_setaffinity() method # importing os module import os # Get the number of CPUs# in the system# using os.cpu_count() methodprint(\"Number of CPUs:\", os.cpu_count()) # Get the set of CPUs# on which the calling process# is eligible to run. using# os.sched_getaffinity() method# 0 as PID represents the# calling processpid = 0affinity = os.sched_getaffinity(pid) # Print the resultprint(\"Process is eligible to run on:\", affinity) # Change the CPU affinity mask# of the calling process# using os.sched_setaffinity() method # Below CPU affinity mask will# restrict a process to only# these 2 CPUs (0, 1) i.e process can# run on these CPUs onlyaffinity_mask = {0, 1}pid = 0os.sched_setaffinity(0, affinity_mask)print(\"CPU affinity mask is modified for process id % s\" % pid) # Now again, Get the set of CPUs# on which the calling process# is eligible to run.pid = 0affinity = os.sched_getaffinity(pid) # Print the resultprint(\"Now, process is eligible to run on:\", affinity)", "e": 1958, "s": 939, "text": null }, { "code": null, "e": 2111, "s": 1958, "text": "Number of CPUs: 4\nProcess is eligible to run on: {0, 1, 2, 3}\nCPU affinity mask is modified for process id 0\nNow, process is eligible to run on: {0, 1}\n" }, { "code": null, "e": 2123, "s": 2111, "text": "References:" }, { "code": null, "e": 2186, "s": 2123, "text": "https://docs.python.org/3/library/os.html#os.sched_setaffinity" }, { "code": null, "e": 2232, "s": 2186, "text": "https://linux.die.net/man/2/sched_getaffinity" }, { "code": null, "e": 2247, "s": 2232, "text": "adnanirshad158" }, { "code": null, "e": 2255, "s": 2247, "text": "clintra" }, { "code": null, "e": 2272, "s": 2255, "text": "python-os-module" }, { "code": null, "e": 2279, "s": 2272, "text": "Python" }, { "code": null, "e": 2377, "s": 2279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2409, "s": 2377, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2436, "s": 2409, "text": "Python Classes and Objects" }, { "code": null, "e": 2467, "s": 2436, "text": "Python | os.path.join() method" }, { "code": null, "e": 2490, "s": 2467, "text": "Introduction To PYTHON" }, { "code": null, "e": 2511, "s": 2490, "text": "Python OOPs Concepts" }, { "code": null, "e": 2567, "s": 2511, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2609, "s": 2567, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2651, "s": 2609, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2690, "s": 2651, "text": "Python | Get unique values from a list" } ]
How to Select date from a datepicker with Selenium Webdriver using Python?
We can select a date from a datepicker with Selenium webdriver using Python. To identify a particular date, first we have to use the find_elements method and identify all the dates having a common locator value. The find_elements returns a list of matching elements. We have to iterate through this list and search for the date which meets our criteria. Once we get that date, we would select it. Then break out from this iteration. from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://jqueryui.com/datepicker/") #switch to frame l = driver.find_element_by_xpath("//iframe[@class='demo-frame']") driver.switch_to.frame(l); #identify element inside frame d= driver.find_element_by_id("datepicker") d.click() #identify list of all dates m = driver.find_elements_by_xpath("//table/tbody/tr/td") #iterate over list for i in m: #verify required date then click if i.text == '3': i.click() break #get selected date s = d.get_attribute('value') print("Date entered is: ") print(s) #browser quit driver.quit()
[ { "code": null, "e": 1399, "s": 1187, "text": "We can select a date from a datepicker with Selenium webdriver using Python. To identify a particular date, first we have to use the find_elements method and identify all the dates having a common locator value." }, { "code": null, "e": 1620, "s": 1399, "text": "The find_elements returns a list of matching elements. We have to iterate through this list and search for the date which meets our criteria. Once we get that date, we would select it. Then break out from this iteration." }, { "code": null, "e": 2332, "s": 1620, "text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://jqueryui.com/datepicker/\")\n#switch to frame\nl = driver.find_element_by_xpath(\"//iframe[@class='demo-frame']\")\ndriver.switch_to.frame(l);\n#identify element inside frame\nd= driver.find_element_by_id(\"datepicker\")\nd.click()\n#identify list of all dates\nm = driver.find_elements_by_xpath(\"//table/tbody/tr/td\")\n#iterate over list\nfor i in m:\n#verify required date then click\n if i.text == '3':\n i.click()\n break\n#get selected date\ns = d.get_attribute('value')\nprint(\"Date entered is: \")\nprint(s)\n#browser quit\ndriver.quit()" } ]
Interface in Java
An interface is a reference type in Java. It is similar to a class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface is similar to a class in the following ways − An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. However, an interface is different from a class in several ways, including − You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. Declaring Interfaces The interface keyword is used to declare an interface. Here is a simple example to declare an interface − Example Following is an example of an interface − /* File name : NameOfInterface.java */ import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations }
[ { "code": null, "e": 1386, "s": 1187, "text": "An interface is a reference type in Java. It is similar to a class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface." }, { "code": null, "e": 1572, "s": 1386, "text": "Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods." }, { "code": null, "e": 1750, "s": 1572, "text": "Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements." }, { "code": null, "e": 1876, "s": 1750, "text": "Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class." }, { "code": null, "e": 1935, "s": 1876, "text": "An interface is similar to a class in the following ways −" }, { "code": null, "e": 1983, "s": 1935, "text": "An interface can contain any number of methods." }, { "code": null, "e": 2103, "s": 1983, "text": "An interface is written in a file with a .java extension, with the name of the interface matching the name of the file." }, { "code": null, "e": 2159, "s": 2103, "text": "The byte code of an interface appears in a .class file." }, { "code": null, "e": 2292, "s": 2159, "text": "Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name." }, { "code": null, "e": 2369, "s": 2292, "text": "However, an interface is different from a class in several ways, including −" }, { "code": null, "e": 2406, "s": 2369, "text": "You cannot instantiate an interface." }, { "code": null, "e": 2454, "s": 2406, "text": "An interface does not contain any constructors." }, { "code": null, "e": 2503, "s": 2454, "text": "All of the methods in an interface are abstract." }, { "code": null, "e": 2636, "s": 2503, "text": "An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final." }, { "code": null, "e": 2707, "s": 2636, "text": "An interface is not extended by a class; it is implemented by a class." }, { "code": null, "e": 2752, "s": 2707, "text": "An interface can extend multiple interfaces." }, { "code": null, "e": 2773, "s": 2752, "text": "Declaring Interfaces" }, { "code": null, "e": 2879, "s": 2773, "text": "The interface keyword is used to declare an interface. Here is a simple example to declare an interface −" }, { "code": null, "e": 2887, "s": 2879, "text": "Example" }, { "code": null, "e": 2930, "s": 2887, "text": "Following is an example of an interface − " }, { "code": null, "e": 3151, "s": 2930, "text": "/* File name : NameOfInterface.java */\nimport java.lang.*;\n// Any number of import statements\npublic interface NameOfInterface {\n // Any number of final, static fields //\n Any number of abstract method declarations\n}" } ]