title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to add 2 hours to a JavaScript Date object? | To add hours to a JavaScript Date object, use the setHours() method. Under that, get the current hours and 2 hours to it. JavaScript date setHours() method sets the hours for a specified date according to local time.
You can try to run the following code to add 2 hours to date.
Live Demo
<html>
<head>
<title>JavaScript setHours Method</title>
</head>
<body>
<script>
var dt = new Date();
dt.setHours( dt.getHours() + 2 );
document.write( dt );
</script>
</body>
</html>
Sat Dec 15 2018 15:49:50 GMT+0530 (India Standard Time) | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "To add hours to a JavaScript Date object, use the setHours() method. Under that, get the current hours and 2 hours to it. JavaScript date setHours() method sets the hours for a specified date according to local time."
},
{
"code": null,
"e": 1341,
"s": 1279,
"text": "You can try to run the following code to add 2 hours to date."
},
{
"code": null,
"e": 1352,
"s": 1341,
"text": " Live Demo"
},
{
"code": null,
"e": 1592,
"s": 1352,
"text": "<html>\n <head>\n <title>JavaScript setHours Method</title>\n </head>\n <body>\n <script>\n var dt = new Date();\n dt.setHours( dt.getHours() + 2 );\n document.write( dt );\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1648,
"s": 1592,
"text": "Sat Dec 15 2018 15:49:50 GMT+0530 (India Standard Time)"
}
]
|
How to extract all the .txt files from a zip file using Python? | In order to extract all .txt files from a zip, you'll need to loop over all files in the zipfile, check if a file is txt file or not. If it is a txt file then extract it. For this we'll use the zipfile module and its extract function.
import zipfile
my_zip = zipfile.Zipfile('my_zip_file.zip') # Specify your zip file's name here
storage_path = '.'
for file in my_zip.namelist():
if my_zip.getinfo(file).filename.endswith('.txt'):
my_zip.extract(file, storage_path) # extract the file to current folder if it is a text file
Running the above code will open the my_zip_file.zip and extract all txt files from it and store them in the current directory. | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "In order to extract all .txt files from a zip, you'll need to loop over all files in the zipfile, check if a file is txt file or not. If it is a txt file then extract it. For this we'll use the zipfile module and its extract function."
},
{
"code": null,
"e": 1598,
"s": 1297,
"text": "import zipfile\nmy_zip = zipfile.Zipfile('my_zip_file.zip') # Specify your zip file's name here\nstorage_path = '.'\nfor file in my_zip.namelist():\n if my_zip.getinfo(file).filename.endswith('.txt'):\n my_zip.extract(file, storage_path) # extract the file to current folder if it is a text file"
},
{
"code": null,
"e": 1726,
"s": 1598,
"text": "Running the above code will open the my_zip_file.zip and extract all txt files from it and store them in the current directory."
}
]
|
Bokeh - Server | Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library.
However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser.
A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session.
First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency.
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data = dict(x = x, y = y))
plot = figure(plot_height = 400, plot_width = 400, title = "sine wave")
plot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)
freq = Slider(title = "frequency", value = 1.0, start = 0.1, end = 5.1, step = 0.1)
def update_data(attrname, old, new):
a = 1
b = 0
w = 0
k = freq.value
x = np.linspace(0, 4*np.pi, N)
y = a*np.sin(k*x + w) + b
source.data = dict(x = x, y = y)
freq.on_change('value', update_data)
curdoc().add_root(row(freq, plot, width = 500))
curdoc().title = "Sliders"
Next, start Bokeh server by following command line −
Bokeh serve –show sliders.py
Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display −
C:\Users\User>bokeh serve --show scripts\sliders.py
2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)
2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders
2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776
2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms
2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms
2019-09-29 00:21:38,045 WebSocket connection opened
2019-09-29 00:21:38,049 ServerConnection created
Open your favourite browser and enter above address. The Sine wave plot is displayed as follows −
You can try and change the frequency to 2 by rolling the slider.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2442,
"s": 2270,
"text": "Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library."
},
{
"code": null,
"e": 2766,
"s": 2442,
"text": "However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser."
},
{
"code": null,
"e": 2967,
"s": 2766,
"text": "A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session."
},
{
"code": null,
"e": 3315,
"s": 2967,
"text": "First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency."
},
{
"code": null,
"e": 4153,
"s": 3315,
"text": "import numpy as np\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import row, column\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.models.widgets import Slider, TextInput\nfrom bokeh.plotting import figure\nN = 200\nx = np.linspace(0, 4*np.pi, N)\ny = np.sin(x)\nsource = ColumnDataSource(data = dict(x = x, y = y))\nplot = figure(plot_height = 400, plot_width = 400, title = \"sine wave\")\nplot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)\nfreq = Slider(title = \"frequency\", value = 1.0, start = 0.1, end = 5.1, step = 0.1)\ndef update_data(attrname, old, new):\n a = 1\n b = 0\n w = 0\n k = freq.value\n x = np.linspace(0, 4*np.pi, N)\n y = a*np.sin(k*x + w) + b\n source.data = dict(x = x, y = y)\nfreq.on_change('value', update_data)\ncurdoc().add_root(row(freq, plot, width = 500))\ncurdoc().title = \"Sliders\""
},
{
"code": null,
"e": 4206,
"s": 4153,
"text": "Next, start Bokeh server by following command line −"
},
{
"code": null,
"e": 4236,
"s": 4206,
"text": "Bokeh serve –show sliders.py\n"
},
{
"code": null,
"e": 4365,
"s": 4236,
"text": "Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display −"
},
{
"code": null,
"e": 4952,
"s": 4365,
"text": "C:\\Users\\User>bokeh serve --show scripts\\sliders.py\n2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)\n2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders\n2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776\n2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms\n2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms\n2019-09-29 00:21:38,045 WebSocket connection opened\n2019-09-29 00:21:38,049 ServerConnection created\n"
},
{
"code": null,
"e": 5050,
"s": 4952,
"text": "Open your favourite browser and enter above address. The Sine wave plot is displayed as follows −"
},
{
"code": null,
"e": 5115,
"s": 5050,
"text": "You can try and change the frequency to 2 by rolling the slider."
},
{
"code": null,
"e": 5122,
"s": 5115,
"text": " Print"
},
{
"code": null,
"e": 5133,
"s": 5122,
"text": " Add Notes"
}
]
|
Sentiment Analysis / Text Classification Using CNN (Convolutional Neural Network) | by Saad Arshad | Towards Data Science | There are lots of applications of text classification. For example, hate speech detection, intent classification, and organizing news articles. The focus of this article is Sentiment Analysis which is a text classification problem. We will be classifying the IMDB comments into two classes i.e. positive and negative.
We use Python and Jupyter Notebook to develop our system, the libraries we will use include Keras, Gensim, Numpy, Pandas, Regex(re) and NLTK. We will also use Google News Word2Vec Model. The complete code and data can be downloaded from here.
First, we have a look at our data. As the data file is a tab-separated file(tsv), we will read it by using pandas and pass arguments to tell the function that the delimiter is tab and there is no header in our data file. Then we set the header of our data frame.
import pandas as pddata = pd.read_csv('imdb_labelled.tsv', header = None, delimiter='\t')data.columns = ['Text', 'Label']df.head()
Then we check the shape of data
data.shape
Now we see the class distribution. We have 386 positive and 362 negative examples.
data.Label.value_counts()
The first step in data cleaning is to remove punctuation marks. We simply do it by using Regex. After removing the punctuation marks the data is saved in the same data frame.
import redef remove_punct(text): text_nopunct = '' text_nopunct = re.sub('['+string.punctuation+']', '', text) return text_nopunctdata['Text_Clean'] = data['Text'].apply(lambda x: remove_punct(x))
In the next step, we tokenize the comments by using NLTK’s word_tokenize. If we pass a string ‘Tokenizing is easy’ to word_tokenize. The output is [‘Tokenizing’, ‘is’, ‘easy’]
from nltk import word_tokenizetokens = [word_tokenize(sen) for sen in data.Text_Clean]
Then we lower case the data.
def lower_token(tokens): return [w.lower() for w in tokens] lower_tokens = [lower_token(token) for token in tokens]
After lower casing the data, stop words are removed from data using NLTK’s stopwords.
from nltk.corpus import stopwordsstoplist = stopwords.words('english')def removeStopWords(tokens): return [word for word in tokens if word not in stoplist]filtered_words = [removeStopWords(sen) for sen in lower_tokens]data['Text_Final'] = [' '.join(sen) for sen in filtered_words]data['tokens'] = filtered_words
As our problem is a binary classification. We need to pass our model a two-dimensional output vector. For that, we add two one hot encoded columns to our data frame.
pos = []neg = []for l in data.Label: if l == 0: pos.append(0) neg.append(1) elif l == 1: pos.append(1) neg.append(0)data['Pos']= posdata['Neg']= negdata = data[['Text_Final', 'tokens', 'Label', 'Pos', 'Neg']]data.head()
Now we split our data set into train and test. We will use 90 % data for training and 10 % for testing. We use random state so every time we get the same training and testing data.
data_train, data_test = train_test_split(data, test_size=0.10, random_state=42)
Then we build training vocabulary and get maximum training sentence length and total number of words training data.
all_training_words = [word for tokens in data_train["tokens"] for word in tokens]training_sentence_lengths = [len(tokens) for tokens in data_train["tokens"]]TRAINING_VOCAB = sorted(list(set(all_training_words)))print("%s words total, with a vocabulary size of %s" % (len(all_training_words), len(TRAINING_VOCAB)))print("Max sentence length is %s" % max(training_sentence_lengths))
Then we build testing vocabulary and get maximum testing sentence length and total number of words in testing data.
all_test_words = [word for tokens in data_test[“tokens”] for word in tokens]test_sentence_lengths = [len(tokens) for tokens in data_test[“tokens”]]TEST_VOCAB = sorted(list(set(all_test_words)))print(“%s words total, with a vocabulary size of %s” % (len(all_test_words), len(TEST_VOCAB)))print(“Max sentence length is %s” % max(test_sentence_lengths))
Now we will load the Google News Word2Vec model. This step may take some time. You can use any other pre-trained word embeddings or train your own word embeddings if you have sufficient amount of data.
word2vec_path = 'GoogleNews-vectors-negative300.bin.gz'word2vec = models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)
Each word is assigned an integer and that integer is placed in a list. As all the training sentences must have same input shape we pad the sentences.
For example if we have a sentence “How text to sequence and padding works”. Each word is assigned a number. We suppose how = 1, text = 2, to = 3, sequence =4, and = 5, padding = 6, works = 7. After texts_to_sequences is called our sentence will look like [1, 2, 3, 4, 5, 6, 7 ]. Now we suppose our MAX_SEQUENCE_LENGTH = 10. After padding our sentence will look like [0, 0, 0, 1, 2, 3, 4, 5, 6, 7 ]
We do same for testing data also. For complete code visit.
tokenizer = Tokenizer(num_words=len(TRAINING_VOCAB), lower=True, char_level=False)tokenizer.fit_on_texts(data_train[“Text_Final”].tolist())training_sequences = tokenizer.texts_to_sequences(data_train[“Text_Final”].tolist())train_word_index = tokenizer.word_indexprint(‘Found %s unique tokens.’ % len(train_word_index))train_cnn_data = pad_sequences(training_sequences, maxlen=MAX_SEQUENCE_LENGTH)
Now we will get embeddings from Google News Word2Vec model and save them corresponding to the sequence number we assigned to each word. If we could not get embeddings we save a random vector for that word.
train_embedding_weights = np.zeros((len(train_word_index)+1, EMBEDDING_DIM))for word,index in train_word_index.items(): train_embedding_weights[index,:] = word2vec[word] if word in word2vec else np.random.rand(EMBEDDING_DIM)print(train_embedding_weights.shape)
Text as a sequence is passed to a CNN. The embeddings matrix is passed to embedding_layer. Five different filter sizes are applied to each comment, and GlobalMaxPooling1D layers are applied to each layer. All the outputs are then concatenated. A Dropout layer then Dense then Dropout and then Final Dense layer is applied.
model.summary() will print a brief summary of all the layers with there output shapes.
def ConvNet(embeddings, max_sequence_length, num_words, embedding_dim, labels_index): embedding_layer = Embedding(num_words, embedding_dim, weights=[embeddings], input_length=max_sequence_length, trainable=False) sequence_input = Input(shape=(max_sequence_length,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) convs = [] filter_sizes = [2,3,4,5,6] for filter_size in filter_sizes: l_conv = Conv1D(filters=200, kernel_size=filter_size, activation='relu')(embedded_sequences) l_pool = GlobalMaxPooling1D()(l_conv) convs.append(l_pool) l_merge = concatenate(convs, axis=1) x = Dropout(0.1)(l_merge) x = Dense(128, activation='relu')(x) x = Dropout(0.2)(x) preds = Dense(labels_index, activation='sigmoid')(x) model = Model(sequence_input, preds) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc']) model.summary() return model
Now we will execute the function.
model = ConvNet(train_embedding_weights, MAX_SEQUENCE_LENGTH, len(train_word_index)+1, EMBEDDING_DIM, len(list(label_names)))
The number of epochs is the amount to which your model will loop around and learn, and batch size is the amount of data which your model will see at a single time. As we are training on small data set in just a few epochs out model will over fit.
num_epochs = 3batch_size = 32hist = model.fit(x_train, y_tr, epochs=num_epochs, validation_split=0.1, shuffle=True, batch_size=batch_size)
Wow! with just three iterations and a small data set we were able to get 84 % accuracy.
predictions = model.predict(test_cnn_data, batch_size=1024, verbose=1)labels = [1, 0]prediction_labels=[]for p in predictions: prediction_labels.append(labels[np.argmax(p)])sum(data_test.Label==prediction_labels)/len(prediction_labels) | [
{
"code": null,
"e": 490,
"s": 172,
"text": "There are lots of applications of text classification. For example, hate speech detection, intent classification, and organizing news articles. The focus of this article is Sentiment Analysis which is a text classification problem. We will be classifying the IMDB comments into two classes i.e. positive and negative."
},
{
"code": null,
"e": 733,
"s": 490,
"text": "We use Python and Jupyter Notebook to develop our system, the libraries we will use include Keras, Gensim, Numpy, Pandas, Regex(re) and NLTK. We will also use Google News Word2Vec Model. The complete code and data can be downloaded from here."
},
{
"code": null,
"e": 996,
"s": 733,
"text": "First, we have a look at our data. As the data file is a tab-separated file(tsv), we will read it by using pandas and pass arguments to tell the function that the delimiter is tab and there is no header in our data file. Then we set the header of our data frame."
},
{
"code": null,
"e": 1165,
"s": 996,
"text": "import pandas as pddata = pd.read_csv('imdb_labelled.tsv', header = None, delimiter='\\t')data.columns = ['Text', 'Label']df.head()"
},
{
"code": null,
"e": 1197,
"s": 1165,
"text": "Then we check the shape of data"
},
{
"code": null,
"e": 1208,
"s": 1197,
"text": "data.shape"
},
{
"code": null,
"e": 1291,
"s": 1208,
"text": "Now we see the class distribution. We have 386 positive and 362 negative examples."
},
{
"code": null,
"e": 1317,
"s": 1291,
"text": "data.Label.value_counts()"
},
{
"code": null,
"e": 1492,
"s": 1317,
"text": "The first step in data cleaning is to remove punctuation marks. We simply do it by using Regex. After removing the punctuation marks the data is saved in the same data frame."
},
{
"code": null,
"e": 1698,
"s": 1492,
"text": "import redef remove_punct(text): text_nopunct = '' text_nopunct = re.sub('['+string.punctuation+']', '', text) return text_nopunctdata['Text_Clean'] = data['Text'].apply(lambda x: remove_punct(x))"
},
{
"code": null,
"e": 1874,
"s": 1698,
"text": "In the next step, we tokenize the comments by using NLTK’s word_tokenize. If we pass a string ‘Tokenizing is easy’ to word_tokenize. The output is [‘Tokenizing’, ‘is’, ‘easy’]"
},
{
"code": null,
"e": 1961,
"s": 1874,
"text": "from nltk import word_tokenizetokens = [word_tokenize(sen) for sen in data.Text_Clean]"
},
{
"code": null,
"e": 1990,
"s": 1961,
"text": "Then we lower case the data."
},
{
"code": null,
"e": 2117,
"s": 1990,
"text": "def lower_token(tokens): return [w.lower() for w in tokens] lower_tokens = [lower_token(token) for token in tokens]"
},
{
"code": null,
"e": 2203,
"s": 2117,
"text": "After lower casing the data, stop words are removed from data using NLTK’s stopwords."
},
{
"code": null,
"e": 2519,
"s": 2203,
"text": "from nltk.corpus import stopwordsstoplist = stopwords.words('english')def removeStopWords(tokens): return [word for word in tokens if word not in stoplist]filtered_words = [removeStopWords(sen) for sen in lower_tokens]data['Text_Final'] = [' '.join(sen) for sen in filtered_words]data['tokens'] = filtered_words"
},
{
"code": null,
"e": 2685,
"s": 2519,
"text": "As our problem is a binary classification. We need to pass our model a two-dimensional output vector. For that, we add two one hot encoded columns to our data frame."
},
{
"code": null,
"e": 2939,
"s": 2685,
"text": "pos = []neg = []for l in data.Label: if l == 0: pos.append(0) neg.append(1) elif l == 1: pos.append(1) neg.append(0)data['Pos']= posdata['Neg']= negdata = data[['Text_Final', 'tokens', 'Label', 'Pos', 'Neg']]data.head()"
},
{
"code": null,
"e": 3120,
"s": 2939,
"text": "Now we split our data set into train and test. We will use 90 % data for training and 10 % for testing. We use random state so every time we get the same training and testing data."
},
{
"code": null,
"e": 3282,
"s": 3120,
"text": "data_train, data_test = train_test_split(data, test_size=0.10, random_state=42)"
},
{
"code": null,
"e": 3398,
"s": 3282,
"text": "Then we build training vocabulary and get maximum training sentence length and total number of words training data."
},
{
"code": null,
"e": 3779,
"s": 3398,
"text": "all_training_words = [word for tokens in data_train[\"tokens\"] for word in tokens]training_sentence_lengths = [len(tokens) for tokens in data_train[\"tokens\"]]TRAINING_VOCAB = sorted(list(set(all_training_words)))print(\"%s words total, with a vocabulary size of %s\" % (len(all_training_words), len(TRAINING_VOCAB)))print(\"Max sentence length is %s\" % max(training_sentence_lengths))"
},
{
"code": null,
"e": 3895,
"s": 3779,
"text": "Then we build testing vocabulary and get maximum testing sentence length and total number of words in testing data."
},
{
"code": null,
"e": 4246,
"s": 3895,
"text": "all_test_words = [word for tokens in data_test[“tokens”] for word in tokens]test_sentence_lengths = [len(tokens) for tokens in data_test[“tokens”]]TEST_VOCAB = sorted(list(set(all_test_words)))print(“%s words total, with a vocabulary size of %s” % (len(all_test_words), len(TEST_VOCAB)))print(“Max sentence length is %s” % max(test_sentence_lengths))"
},
{
"code": null,
"e": 4448,
"s": 4246,
"text": "Now we will load the Google News Word2Vec model. This step may take some time. You can use any other pre-trained word embeddings or train your own word embeddings if you have sufficient amount of data."
},
{
"code": null,
"e": 4583,
"s": 4448,
"text": "word2vec_path = 'GoogleNews-vectors-negative300.bin.gz'word2vec = models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)"
},
{
"code": null,
"e": 4733,
"s": 4583,
"text": "Each word is assigned an integer and that integer is placed in a list. As all the training sentences must have same input shape we pad the sentences."
},
{
"code": null,
"e": 5131,
"s": 4733,
"text": "For example if we have a sentence “How text to sequence and padding works”. Each word is assigned a number. We suppose how = 1, text = 2, to = 3, sequence =4, and = 5, padding = 6, works = 7. After texts_to_sequences is called our sentence will look like [1, 2, 3, 4, 5, 6, 7 ]. Now we suppose our MAX_SEQUENCE_LENGTH = 10. After padding our sentence will look like [0, 0, 0, 1, 2, 3, 4, 5, 6, 7 ]"
},
{
"code": null,
"e": 5190,
"s": 5131,
"text": "We do same for testing data also. For complete code visit."
},
{
"code": null,
"e": 5618,
"s": 5190,
"text": "tokenizer = Tokenizer(num_words=len(TRAINING_VOCAB), lower=True, char_level=False)tokenizer.fit_on_texts(data_train[“Text_Final”].tolist())training_sequences = tokenizer.texts_to_sequences(data_train[“Text_Final”].tolist())train_word_index = tokenizer.word_indexprint(‘Found %s unique tokens.’ % len(train_word_index))train_cnn_data = pad_sequences(training_sequences, maxlen=MAX_SEQUENCE_LENGTH)"
},
{
"code": null,
"e": 5824,
"s": 5618,
"text": "Now we will get embeddings from Google News Word2Vec model and save them corresponding to the sequence number we assigned to each word. If we could not get embeddings we save a random vector for that word."
},
{
"code": null,
"e": 6086,
"s": 5824,
"text": "train_embedding_weights = np.zeros((len(train_word_index)+1, EMBEDDING_DIM))for word,index in train_word_index.items(): train_embedding_weights[index,:] = word2vec[word] if word in word2vec else np.random.rand(EMBEDDING_DIM)print(train_embedding_weights.shape)"
},
{
"code": null,
"e": 6409,
"s": 6086,
"text": "Text as a sequence is passed to a CNN. The embeddings matrix is passed to embedding_layer. Five different filter sizes are applied to each comment, and GlobalMaxPooling1D layers are applied to each layer. All the outputs are then concatenated. A Dropout layer then Dense then Dropout and then Final Dense layer is applied."
},
{
"code": null,
"e": 6496,
"s": 6409,
"text": "model.summary() will print a brief summary of all the layers with there output shapes."
},
{
"code": null,
"e": 7632,
"s": 6496,
"text": "def ConvNet(embeddings, max_sequence_length, num_words, embedding_dim, labels_index): embedding_layer = Embedding(num_words, embedding_dim, weights=[embeddings], input_length=max_sequence_length, trainable=False) sequence_input = Input(shape=(max_sequence_length,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) convs = [] filter_sizes = [2,3,4,5,6] for filter_size in filter_sizes: l_conv = Conv1D(filters=200, kernel_size=filter_size, activation='relu')(embedded_sequences) l_pool = GlobalMaxPooling1D()(l_conv) convs.append(l_pool) l_merge = concatenate(convs, axis=1) x = Dropout(0.1)(l_merge) x = Dense(128, activation='relu')(x) x = Dropout(0.2)(x) preds = Dense(labels_index, activation='sigmoid')(x) model = Model(sequence_input, preds) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc']) model.summary() return model"
},
{
"code": null,
"e": 7666,
"s": 7632,
"text": "Now we will execute the function."
},
{
"code": null,
"e": 7856,
"s": 7666,
"text": "model = ConvNet(train_embedding_weights, MAX_SEQUENCE_LENGTH, len(train_word_index)+1, EMBEDDING_DIM, len(list(label_names)))"
},
{
"code": null,
"e": 8103,
"s": 7856,
"text": "The number of epochs is the amount to which your model will loop around and learn, and batch size is the amount of data which your model will see at a single time. As we are training on small data set in just a few epochs out model will over fit."
},
{
"code": null,
"e": 8327,
"s": 8103,
"text": "num_epochs = 3batch_size = 32hist = model.fit(x_train, y_tr, epochs=num_epochs, validation_split=0.1, shuffle=True, batch_size=batch_size)"
},
{
"code": null,
"e": 8415,
"s": 8327,
"text": "Wow! with just three iterations and a small data set we were able to get 84 % accuracy."
}
]
|
Prefect: How to Write and Schedule Your First ETL Pipeline with Python | by Dario Radečić | Towards Data Science | Prefect is a Python-based workflow management system based on a simple premise — Your code probably works, but sometimes it doesn’t (source). No one thinks about workflow systems when everything works as expected. But when things go south, Prefect will guarantee your code fails successfully.
As a workflow management system, Prefect makes it easy to add logging, retries, dynamic mapping, caching, failure notifications, and more to your data pipelines. It is invisible when you don’t need it — when everything works as expected, and visible when you do. Something like insurance.
While Prefect isn’t the only available workflow management system for Python users, it is undoubtedly the most proficient one. Alternatives such as Apache Airflow usually work well, but introduce a lot of headaches when working on big projects. You can read a detailed comparison between Prefect and Airflow here.
This article covers the basics of the library, such as tasks, flows, parameters, failures, and schedules, and also explains how to set up the environment both locally and in the cloud. We’ll use Saturn Cloud for that part, as it makes the configuration effortless. It is a cloud platform made by data scientists, so most of the heavy lifting is done for you.
Saturn Cloud can handle Prefect workflows without breaking a sweat. It is also a cutting-edge solution for anything from dashboards to distributed machine learning, deep learning, and GPU training.
Today you’ll learn how to:
Install Prefect locally
Write a simple ETL pipeline with Python
Use Prefect to declare tasks, flows, parameters, schedules and handle failures
Run Prefect in Saturn Cloud
We’ll install the Prefect library inside a virtual environment. The following commands will create and activate the environment named prefect_env through Anaconda, based on Python 3.8:
conda create — name prefect_env python=3.8conda activate prefect_env
You’ll have to enter y a couple of times to instruct Anaconda to proceed, but that’s the case with every installation. Library-wise, we’ll need Pandas for data manipulation, Requests for downloading the data, and of course, Prefect for workflow management:
conda install requests pandasconda install -c conda-forge prefect
We now have everything needed to start writing Python code. Let’s do that next.
We’ll use Prefect to complete a relatively simple task today — run an ETL pipeline. This pipeline will download the data from a dummy API, transform it, and save it as a CSV. The JSON Placeholder website will serve as our dummy API. Among other things, it contains fake data for ten users:
Let’s start by creating a Python file — I’ve named mine 01_etl_pipeline.py. Also, make sure to have a folder where extracted and transformed data will be saved. I’ve called it data, and it’s located right where the Python scripts are.
Any ETL pipeline needs three functions implemented — for extracting, transforming, and loading the data. Here’s what these functions will do in our case:
extract(url: str) -> dict — makes a GET request to the url parameter. Tests to see if some data was returned — in that case, it is returned as a dictionary. Otherwise, an exception is raised.
transform(data: dict) -> pd.DataFrame — transforms the data so only specific attributes are kept: ID, name, username, email, address, phone number, and company. Returns the transformed data as a Pandas DataFrame.
load(data: pd.DataFrame, path: str) -> None — saves the previously transformed data to a CSV file at path. We’ll also append a timestamp to the file name, so the files don’t get overwritten.
After function declaration, all three are called when the Python script is executed. Here’s the complete code snippet:
You can now run the script by executing the following from the Terminal:
python 01_etl_pipeline.py
You shouldn’t see any output if everything ran correctly. However, you should see CSV file(s) in the data folder (I’ve run the file twice):
As you can see, the ETL pipeline runs and finishes without any errors. But what if you want to run the pipeline at a schedule? That’s where Prefect comes in.
In this section, you’ll learn the basics of Prefect tasks, flows, parameters, schedules, and much more.
Let’s start with the most simple one — tasks. It’s basically a single step of your workflow. To follow along, create a new Python file called 02_task_conversion.py. Copy everything from 01_etl_pipeline.py, and you’re ready to go.
To convert a Python function to a Prefect Task, you first need to make the necessary import — from prefect import task, and decorate any function of interest. Here’s an example:
@taskdef my_function(): pass
That’s all you have to do! Here’s the updated version of our ETL pipeline:
Let’s run it and see what happens:
python 02_task_conversion.py
It looks like something is wrong. That’s because Prefect Task can’t be run without the Prefect Flow. Let’s implement it next.
Copy everything from 02_task_conversion.py to a new file — 03_flow.py. You’ll need to import Flow from the prefect library before declaring it.
To declare a Flow, we’ll write another Python function — prefect_flow(). It won’t accept any parameters and won’t be decorated with anything. Inside the function, we’ll use Python’s context manager to create a flow. The flow should contain the same three lines that were previously inside the if __name__ == ‘__main__” code block.
In the mentioned block, we’ll now have to run the flow with the corresponding run() function.
Here’s the complete code for this file:
Let’s run it and see what happens:
python 03_flow.py
Now that’s something! Not only is the ETL pipeline executed, but we also get detailed information about when every task started and finished. I’ve run the file twice, so two new CSV files should get saved to the data folder. Let’s verify if that’s the case:
And that’s how you can run a simple ETL pipeline with Prefect. It doesn’t have many benefits over a pure Python implementation yet, but we’ll change that quickly.
Hardcoding parameter values is never a good idea. That’s where Prefect Parameters come in. To start, copy everything from 03_flow.py to a new file — 04_parameters.py. You’ll need to import the Parameter class from the prefect package.
You can use this class inside the flow context manager. Here are the arguments you’ll find helpful:
name — name of the parameter, will be used later upon running the flow.
required — a boolean value, specifies if the parameter is required for the flow to execute.
default — specifies the default value for the parameter.
We’ll declare a parameter for the API URL — param_url = Parameter(name=’p_url’, required=True).
To assign values to the parameters, you’ll need to specify the parameters dictionary as an argument to the run() function. Parameter names and values should be written as key-value pairs.
Here’s the complete code for this file:
Let’s run the file and see what happens:
python 04_parameters.py
I’ve run the file twice, so two new CSV files should appear in the data folder. Let’s verify if that’s true:
And there you have it — parameter value specification at one place. It makes it easy to make changes down the road and also to manage more complex workflows.
Up next, we’ll explore a feature of Prefect that makes it particularly useful — schedules.
We’ll explore two ways to schedule tasks today — Interval schedule and Cron schedule. The second one might sound familiar, as Cron is a well-known method of scheduling tasks on Unix.
We’ll begin with the Interval Scheduler. To start, copy everything from 04_intervals.py to 05_interval_scheduler.py. You’ll have to import IntervalScheduler from prefect.schedules.
Then, we’ll make an instance of the imported class right before the prefect_flow() function declaration and instruct it to run every ten seconds. That can be done by setting the value of the interval parameter.
To connect a scheduler to the workflow, you’ll have to specify the value for the schedule parameter when initializing the Flow class with the context manager.
The whole script file should look like this:
Let’s run the file and see what happens:
python 05_interval_scheduler.py
As you can see, the entire ETL pipeline ran two times. Prefect will report to the Terminal when the next execution will occur.
Now, let’s explore the Cron Scheduler. Copy everything from 05_interval_scheduler.py to 06_cron_scheduler.py. This time you’ll import CronSchedule instead of IntervalSchedule.
Upon class initialization, you’ll specify a cron pattern to the cron parameter. Five star symbols will ensure the workflow runs every minute. That’s the lowest possible interval with Cron.
The rest of the file remains identical. Here’s the code:
Let’s run the file:
python 06_cron_scheduler.py
As you can see, the ETL pipeline was run twice every full minute, as specified by the Cron pattern. For the final part of this section, we’ll explore how to handle failure — and explain why you should always prepare for it.
Sooner or later, an unexpected error will happen in your workflow. Prefect provides a ridiculously easy way to retry the execution of a task. To start, copy everything from 04_parameters.py to a new file — 07_failures.py.
The extract() function could fail for different network reasons. For example, maybe the API isn’t available at the moment but will be in a couple of seconds. These things happen in a production environment and shouldn’t crash your application altogether.
To avoid unwanted crashes, we can extend our task decorator a bit. It can accept different parameters, and today we’ll use max_retries and retry_delay. Both are self-explanatory, so I won’t bother with further explanation.
The only problem is — our workflow won’t fail as is. But it will if we place a non-existing URL as a parameter value inside flow.run(). Here’s the code:
Let’s run the file:
python 07_failures.py
The task failed, but the workflow didn’t crash. Of course, it will crash after ten retries, but you can always change the parameter specification.
And that does it for working with Prefect locally. Next, let’s move our code to the cloud and explore the changes.
Let’s get our hands dirty right away. To start, sign up for a free version of a Prefect Cloud account. The registration process is straightforward and requires no further explanation. Once registered, create a project. I’ve named mine SaturnCloudDemo.
Before going over to Saturn Cloud, you’ll have to create an API key in Prefect that will connect the two. You’ll find the API Key option under settings. As you can see, I’ve named mine SaturnDemoKey:
You now have everything needed, so go over to Saturn Cloud and create a free account. Once on the dashboard, you’ll see multiple options for project creation. Select the Prefect option, like the one you can see below:
Saturn Cloud will now automatically do all the heavy lifting for you, and a couple of minutes later, you’ll be able to open a JupyterLab instance by clicking on the button:
You’ll have access to two notebooks — the second one shows a quick demonstration of using Prefect in Saturn Cloud. Here’s how it looks:
You’ll need to change only two things for a notebook to work. First, change the project name to the name of your project in Prefect Cloud. Second, replace <your_api_key_here> with an API key generated a couple of minutes ago. If you did everything correctly, you should see the following message:
To test, run every cell that follows in the notebook. Then go over to the Prefect Cloud dashboard and open up your project. It won’t be empty as it was a couple of minutes ago:
And that’s all you have to do! Feel free to copy/paste our ETL pipeline and verify that it works. That’s where Saturn Cloud shines — you can copy/paste the code from the local machine with minimal changes, as everything tedious is configured automatically.
Let’s wrap things up in the next section.
And there you have it — the basics of Prefect explained, both locally and on the cloud. I hope you can see the value of workflow management systems for production applications even if you knew nothing about the topic before reading this article.
For more advanced guides, i.e., configuring logging and Slack notifications, please refer to the official documentation. The provided examples are more than enough to get you started.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn | [
{
"code": null,
"e": 465,
"s": 172,
"text": "Prefect is a Python-based workflow management system based on a simple premise — Your code probably works, but sometimes it doesn’t (source). No one thinks about workflow systems when everything works as expected. But when things go south, Prefect will guarantee your code fails successfully."
},
{
"code": null,
"e": 754,
"s": 465,
"text": "As a workflow management system, Prefect makes it easy to add logging, retries, dynamic mapping, caching, failure notifications, and more to your data pipelines. It is invisible when you don’t need it — when everything works as expected, and visible when you do. Something like insurance."
},
{
"code": null,
"e": 1068,
"s": 754,
"text": "While Prefect isn’t the only available workflow management system for Python users, it is undoubtedly the most proficient one. Alternatives such as Apache Airflow usually work well, but introduce a lot of headaches when working on big projects. You can read a detailed comparison between Prefect and Airflow here."
},
{
"code": null,
"e": 1427,
"s": 1068,
"text": "This article covers the basics of the library, such as tasks, flows, parameters, failures, and schedules, and also explains how to set up the environment both locally and in the cloud. We’ll use Saturn Cloud for that part, as it makes the configuration effortless. It is a cloud platform made by data scientists, so most of the heavy lifting is done for you."
},
{
"code": null,
"e": 1625,
"s": 1427,
"text": "Saturn Cloud can handle Prefect workflows without breaking a sweat. It is also a cutting-edge solution for anything from dashboards to distributed machine learning, deep learning, and GPU training."
},
{
"code": null,
"e": 1652,
"s": 1625,
"text": "Today you’ll learn how to:"
},
{
"code": null,
"e": 1676,
"s": 1652,
"text": "Install Prefect locally"
},
{
"code": null,
"e": 1716,
"s": 1676,
"text": "Write a simple ETL pipeline with Python"
},
{
"code": null,
"e": 1795,
"s": 1716,
"text": "Use Prefect to declare tasks, flows, parameters, schedules and handle failures"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "Run Prefect in Saturn Cloud"
},
{
"code": null,
"e": 2008,
"s": 1823,
"text": "We’ll install the Prefect library inside a virtual environment. The following commands will create and activate the environment named prefect_env through Anaconda, based on Python 3.8:"
},
{
"code": null,
"e": 2077,
"s": 2008,
"text": "conda create — name prefect_env python=3.8conda activate prefect_env"
},
{
"code": null,
"e": 2334,
"s": 2077,
"text": "You’ll have to enter y a couple of times to instruct Anaconda to proceed, but that’s the case with every installation. Library-wise, we’ll need Pandas for data manipulation, Requests for downloading the data, and of course, Prefect for workflow management:"
},
{
"code": null,
"e": 2400,
"s": 2334,
"text": "conda install requests pandasconda install -c conda-forge prefect"
},
{
"code": null,
"e": 2480,
"s": 2400,
"text": "We now have everything needed to start writing Python code. Let’s do that next."
},
{
"code": null,
"e": 2770,
"s": 2480,
"text": "We’ll use Prefect to complete a relatively simple task today — run an ETL pipeline. This pipeline will download the data from a dummy API, transform it, and save it as a CSV. The JSON Placeholder website will serve as our dummy API. Among other things, it contains fake data for ten users:"
},
{
"code": null,
"e": 3005,
"s": 2770,
"text": "Let’s start by creating a Python file — I’ve named mine 01_etl_pipeline.py. Also, make sure to have a folder where extracted and transformed data will be saved. I’ve called it data, and it’s located right where the Python scripts are."
},
{
"code": null,
"e": 3159,
"s": 3005,
"text": "Any ETL pipeline needs three functions implemented — for extracting, transforming, and loading the data. Here’s what these functions will do in our case:"
},
{
"code": null,
"e": 3351,
"s": 3159,
"text": "extract(url: str) -> dict — makes a GET request to the url parameter. Tests to see if some data was returned — in that case, it is returned as a dictionary. Otherwise, an exception is raised."
},
{
"code": null,
"e": 3564,
"s": 3351,
"text": "transform(data: dict) -> pd.DataFrame — transforms the data so only specific attributes are kept: ID, name, username, email, address, phone number, and company. Returns the transformed data as a Pandas DataFrame."
},
{
"code": null,
"e": 3755,
"s": 3564,
"text": "load(data: pd.DataFrame, path: str) -> None — saves the previously transformed data to a CSV file at path. We’ll also append a timestamp to the file name, so the files don’t get overwritten."
},
{
"code": null,
"e": 3874,
"s": 3755,
"text": "After function declaration, all three are called when the Python script is executed. Here’s the complete code snippet:"
},
{
"code": null,
"e": 3947,
"s": 3874,
"text": "You can now run the script by executing the following from the Terminal:"
},
{
"code": null,
"e": 3973,
"s": 3947,
"text": "python 01_etl_pipeline.py"
},
{
"code": null,
"e": 4113,
"s": 3973,
"text": "You shouldn’t see any output if everything ran correctly. However, you should see CSV file(s) in the data folder (I’ve run the file twice):"
},
{
"code": null,
"e": 4271,
"s": 4113,
"text": "As you can see, the ETL pipeline runs and finishes without any errors. But what if you want to run the pipeline at a schedule? That’s where Prefect comes in."
},
{
"code": null,
"e": 4375,
"s": 4271,
"text": "In this section, you’ll learn the basics of Prefect tasks, flows, parameters, schedules, and much more."
},
{
"code": null,
"e": 4605,
"s": 4375,
"text": "Let’s start with the most simple one — tasks. It’s basically a single step of your workflow. To follow along, create a new Python file called 02_task_conversion.py. Copy everything from 01_etl_pipeline.py, and you’re ready to go."
},
{
"code": null,
"e": 4783,
"s": 4605,
"text": "To convert a Python function to a Prefect Task, you first need to make the necessary import — from prefect import task, and decorate any function of interest. Here’s an example:"
},
{
"code": null,
"e": 4815,
"s": 4783,
"text": "@taskdef my_function(): pass"
},
{
"code": null,
"e": 4890,
"s": 4815,
"text": "That’s all you have to do! Here’s the updated version of our ETL pipeline:"
},
{
"code": null,
"e": 4925,
"s": 4890,
"text": "Let’s run it and see what happens:"
},
{
"code": null,
"e": 4954,
"s": 4925,
"text": "python 02_task_conversion.py"
},
{
"code": null,
"e": 5080,
"s": 4954,
"text": "It looks like something is wrong. That’s because Prefect Task can’t be run without the Prefect Flow. Let’s implement it next."
},
{
"code": null,
"e": 5224,
"s": 5080,
"text": "Copy everything from 02_task_conversion.py to a new file — 03_flow.py. You’ll need to import Flow from the prefect library before declaring it."
},
{
"code": null,
"e": 5555,
"s": 5224,
"text": "To declare a Flow, we’ll write another Python function — prefect_flow(). It won’t accept any parameters and won’t be decorated with anything. Inside the function, we’ll use Python’s context manager to create a flow. The flow should contain the same three lines that were previously inside the if __name__ == ‘__main__” code block."
},
{
"code": null,
"e": 5649,
"s": 5555,
"text": "In the mentioned block, we’ll now have to run the flow with the corresponding run() function."
},
{
"code": null,
"e": 5689,
"s": 5649,
"text": "Here’s the complete code for this file:"
},
{
"code": null,
"e": 5724,
"s": 5689,
"text": "Let’s run it and see what happens:"
},
{
"code": null,
"e": 5742,
"s": 5724,
"text": "python 03_flow.py"
},
{
"code": null,
"e": 6000,
"s": 5742,
"text": "Now that’s something! Not only is the ETL pipeline executed, but we also get detailed information about when every task started and finished. I’ve run the file twice, so two new CSV files should get saved to the data folder. Let’s verify if that’s the case:"
},
{
"code": null,
"e": 6163,
"s": 6000,
"text": "And that’s how you can run a simple ETL pipeline with Prefect. It doesn’t have many benefits over a pure Python implementation yet, but we’ll change that quickly."
},
{
"code": null,
"e": 6398,
"s": 6163,
"text": "Hardcoding parameter values is never a good idea. That’s where Prefect Parameters come in. To start, copy everything from 03_flow.py to a new file — 04_parameters.py. You’ll need to import the Parameter class from the prefect package."
},
{
"code": null,
"e": 6498,
"s": 6398,
"text": "You can use this class inside the flow context manager. Here are the arguments you’ll find helpful:"
},
{
"code": null,
"e": 6570,
"s": 6498,
"text": "name — name of the parameter, will be used later upon running the flow."
},
{
"code": null,
"e": 6662,
"s": 6570,
"text": "required — a boolean value, specifies if the parameter is required for the flow to execute."
},
{
"code": null,
"e": 6719,
"s": 6662,
"text": "default — specifies the default value for the parameter."
},
{
"code": null,
"e": 6815,
"s": 6719,
"text": "We’ll declare a parameter for the API URL — param_url = Parameter(name=’p_url’, required=True)."
},
{
"code": null,
"e": 7003,
"s": 6815,
"text": "To assign values to the parameters, you’ll need to specify the parameters dictionary as an argument to the run() function. Parameter names and values should be written as key-value pairs."
},
{
"code": null,
"e": 7043,
"s": 7003,
"text": "Here’s the complete code for this file:"
},
{
"code": null,
"e": 7084,
"s": 7043,
"text": "Let’s run the file and see what happens:"
},
{
"code": null,
"e": 7108,
"s": 7084,
"text": "python 04_parameters.py"
},
{
"code": null,
"e": 7217,
"s": 7108,
"text": "I’ve run the file twice, so two new CSV files should appear in the data folder. Let’s verify if that’s true:"
},
{
"code": null,
"e": 7375,
"s": 7217,
"text": "And there you have it — parameter value specification at one place. It makes it easy to make changes down the road and also to manage more complex workflows."
},
{
"code": null,
"e": 7466,
"s": 7375,
"text": "Up next, we’ll explore a feature of Prefect that makes it particularly useful — schedules."
},
{
"code": null,
"e": 7649,
"s": 7466,
"text": "We’ll explore two ways to schedule tasks today — Interval schedule and Cron schedule. The second one might sound familiar, as Cron is a well-known method of scheduling tasks on Unix."
},
{
"code": null,
"e": 7830,
"s": 7649,
"text": "We’ll begin with the Interval Scheduler. To start, copy everything from 04_intervals.py to 05_interval_scheduler.py. You’ll have to import IntervalScheduler from prefect.schedules."
},
{
"code": null,
"e": 8041,
"s": 7830,
"text": "Then, we’ll make an instance of the imported class right before the prefect_flow() function declaration and instruct it to run every ten seconds. That can be done by setting the value of the interval parameter."
},
{
"code": null,
"e": 8200,
"s": 8041,
"text": "To connect a scheduler to the workflow, you’ll have to specify the value for the schedule parameter when initializing the Flow class with the context manager."
},
{
"code": null,
"e": 8245,
"s": 8200,
"text": "The whole script file should look like this:"
},
{
"code": null,
"e": 8286,
"s": 8245,
"text": "Let’s run the file and see what happens:"
},
{
"code": null,
"e": 8318,
"s": 8286,
"text": "python 05_interval_scheduler.py"
},
{
"code": null,
"e": 8445,
"s": 8318,
"text": "As you can see, the entire ETL pipeline ran two times. Prefect will report to the Terminal when the next execution will occur."
},
{
"code": null,
"e": 8621,
"s": 8445,
"text": "Now, let’s explore the Cron Scheduler. Copy everything from 05_interval_scheduler.py to 06_cron_scheduler.py. This time you’ll import CronSchedule instead of IntervalSchedule."
},
{
"code": null,
"e": 8810,
"s": 8621,
"text": "Upon class initialization, you’ll specify a cron pattern to the cron parameter. Five star symbols will ensure the workflow runs every minute. That’s the lowest possible interval with Cron."
},
{
"code": null,
"e": 8867,
"s": 8810,
"text": "The rest of the file remains identical. Here’s the code:"
},
{
"code": null,
"e": 8887,
"s": 8867,
"text": "Let’s run the file:"
},
{
"code": null,
"e": 8915,
"s": 8887,
"text": "python 06_cron_scheduler.py"
},
{
"code": null,
"e": 9139,
"s": 8915,
"text": "As you can see, the ETL pipeline was run twice every full minute, as specified by the Cron pattern. For the final part of this section, we’ll explore how to handle failure — and explain why you should always prepare for it."
},
{
"code": null,
"e": 9361,
"s": 9139,
"text": "Sooner or later, an unexpected error will happen in your workflow. Prefect provides a ridiculously easy way to retry the execution of a task. To start, copy everything from 04_parameters.py to a new file — 07_failures.py."
},
{
"code": null,
"e": 9616,
"s": 9361,
"text": "The extract() function could fail for different network reasons. For example, maybe the API isn’t available at the moment but will be in a couple of seconds. These things happen in a production environment and shouldn’t crash your application altogether."
},
{
"code": null,
"e": 9839,
"s": 9616,
"text": "To avoid unwanted crashes, we can extend our task decorator a bit. It can accept different parameters, and today we’ll use max_retries and retry_delay. Both are self-explanatory, so I won’t bother with further explanation."
},
{
"code": null,
"e": 9992,
"s": 9839,
"text": "The only problem is — our workflow won’t fail as is. But it will if we place a non-existing URL as a parameter value inside flow.run(). Here’s the code:"
},
{
"code": null,
"e": 10012,
"s": 9992,
"text": "Let’s run the file:"
},
{
"code": null,
"e": 10034,
"s": 10012,
"text": "python 07_failures.py"
},
{
"code": null,
"e": 10181,
"s": 10034,
"text": "The task failed, but the workflow didn’t crash. Of course, it will crash after ten retries, but you can always change the parameter specification."
},
{
"code": null,
"e": 10296,
"s": 10181,
"text": "And that does it for working with Prefect locally. Next, let’s move our code to the cloud and explore the changes."
},
{
"code": null,
"e": 10548,
"s": 10296,
"text": "Let’s get our hands dirty right away. To start, sign up for a free version of a Prefect Cloud account. The registration process is straightforward and requires no further explanation. Once registered, create a project. I’ve named mine SaturnCloudDemo."
},
{
"code": null,
"e": 10748,
"s": 10548,
"text": "Before going over to Saturn Cloud, you’ll have to create an API key in Prefect that will connect the two. You’ll find the API Key option under settings. As you can see, I’ve named mine SaturnDemoKey:"
},
{
"code": null,
"e": 10966,
"s": 10748,
"text": "You now have everything needed, so go over to Saturn Cloud and create a free account. Once on the dashboard, you’ll see multiple options for project creation. Select the Prefect option, like the one you can see below:"
},
{
"code": null,
"e": 11139,
"s": 10966,
"text": "Saturn Cloud will now automatically do all the heavy lifting for you, and a couple of minutes later, you’ll be able to open a JupyterLab instance by clicking on the button:"
},
{
"code": null,
"e": 11275,
"s": 11139,
"text": "You’ll have access to two notebooks — the second one shows a quick demonstration of using Prefect in Saturn Cloud. Here’s how it looks:"
},
{
"code": null,
"e": 11572,
"s": 11275,
"text": "You’ll need to change only two things for a notebook to work. First, change the project name to the name of your project in Prefect Cloud. Second, replace <your_api_key_here> with an API key generated a couple of minutes ago. If you did everything correctly, you should see the following message:"
},
{
"code": null,
"e": 11749,
"s": 11572,
"text": "To test, run every cell that follows in the notebook. Then go over to the Prefect Cloud dashboard and open up your project. It won’t be empty as it was a couple of minutes ago:"
},
{
"code": null,
"e": 12006,
"s": 11749,
"text": "And that’s all you have to do! Feel free to copy/paste our ETL pipeline and verify that it works. That’s where Saturn Cloud shines — you can copy/paste the code from the local machine with minimal changes, as everything tedious is configured automatically."
},
{
"code": null,
"e": 12048,
"s": 12006,
"text": "Let’s wrap things up in the next section."
},
{
"code": null,
"e": 12294,
"s": 12048,
"text": "And there you have it — the basics of Prefect explained, both locally and on the cloud. I hope you can see the value of workflow management systems for production applications even if you knew nothing about the topic before reading this article."
},
{
"code": null,
"e": 12478,
"s": 12294,
"text": "For more advanced guides, i.e., configuring logging and Slack notifications, please refer to the official documentation. The provided examples are more than enough to get you started."
},
{
"code": null,
"e": 12661,
"s": 12478,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 12672,
"s": 12661,
"text": "medium.com"
},
{
"code": null,
"e": 12719,
"s": 12672,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 12745,
"s": 12719,
"text": "Sign up for my newsletter"
}
]
|
Understanding Data Science Classification Metrics in Scikit-Learn in Python | by Andrew Long | Towards Data Science | In this tutorial, we will walk through a few of the classifications metrics in Python’s scikit-learn and write our own functions from scratch to understand the math behind a few of them.
One major area of predictive modeling in data science is classification. Classification consists of trying to predict which class a particular sample from a population comes from. For example, if we are trying to predict if a particular patient will be re-hospitalized, the two possible classes are hospital (positive) and not-hospitalized (negative). The classification model then tries to predict if each patient will be hospitalized or not hospitalized. In other words, classification is simply trying to predict which bucket (predicted positive vs predicted negative) a particular sample from the population should be placed as seen below.
As you train your classification predictive model, you will want to assess how good it is. Interestingly, there are many different ways of evaluating the performance. Most data scientists that use Python for predictive modeling use the Python package called scikit-learn. Scikit-learn contains many built-in functions for analyzing the performance of models. In this tutorial, we will walk through a few of these metrics and write our own functions from scratch to understand the math behind a few of them. If you would prefer to just read about performance metrics, please see my previous post at here.
This tutorial will cover the following metrics from sklearn.metrics :
confusion_matrix
accuracy_score
recall_score
precision_score
f1_score
roc_curve
roc_auc_score
For a sample dataset and jupyter notebook, please visit my github here. We will write our own functions from scratch assuming a two-class classification. Note that you will need to fill in the parts tagged as # your code here
Let’s load a sample data set that has the actual labels (actual_label) and the prediction probabilities for two models (model_RF and model_LR). Here the probabilities are the probability of being class 1.
import pandas as pddf = pd.read_csv('data.csv')df.head()
In most data science projects, you will define a threshold to define which prediction probabilities are labeled as predicted positive vs predicted negative. For now let’s assume the threshold is 0.5. Let’s add two additional columns that convert the probabilities to predicted labels.
thresh = 0.5df['predicted_RF'] = (df.model_RF >= 0.5).astype('int')df['predicted_LR'] = (df.model_LR >= 0.5).astype('int')df.head()
Given an actual label and a predicted label, the first thing we can do is divide our samples in 4 buckets:
True positive — actual = 1, predicted = 1
False positive — actual = 0, predicted = 1
False negative — actual = 1, predicted = 0
True negative — actual = 0, predicted = 0
These buckets can be represented with the following image (original source https://en.wikipedia.org/wiki/Precision_and_recall#/media/File:Precisionrecall.svg) and we will reference this image in many of the calculations below.
These buckets can also be displayed using a confusion matrix as shown below:
We can obtain the confusion matrix (as a 2x2 array) from scikit-learn, which takes as inputs the actual labels and the predicted labels
from sklearn.metrics import confusion_matrixconfusion_matrix(df.actual_label.values, df.predicted_RF.values)
where there were 5047 true positives, 2360 false positives, 2832 false negatives and 5519 true negatives. Let’s define our own functions to verify confusion_matrix. Note that I filled in the first one and you need to fill in the other 3.
def find_TP(y_true, y_pred): # counts the number of true positives (y_true = 1, y_pred = 1) return sum((y_true == 1) & (y_pred == 1))def find_FN(y_true, y_pred): # counts the number of false negatives (y_true = 1, y_pred = 0) return # your code heredef find_FP(y_true, y_pred): # counts the number of false positives (y_true = 0, y_pred = 1) return # your code heredef find_TN(y_true, y_pred): # counts the number of true negatives (y_true = 0, y_pred = 0) return # your code here
You can check your results match with
print('TP:',find_TP(df.actual_label.values, df.predicted_RF.values))print('FN:',find_FN(df.actual_label.values, df.predicted_RF.values))print('FP:',find_FP(df.actual_label.values, df.predicted_RF.values))print('TN:',find_TN(df.actual_label.values, df.predicted_RF.values))
Let’s write a function that will calculate all four of these for us, and another function to duplicate confusion_matrix
import numpy as npdef find_conf_matrix_values(y_true,y_pred): # calculate TP, FN, FP, TN TP = find_TP(y_true,y_pred) FN = find_FN(y_true,y_pred) FP = find_FP(y_true,y_pred) TN = find_TN(y_true,y_pred) return TP,FN,FP,TNdef my_confusion_matrix(y_true, y_pred): TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return np.array([[TN,FP],[FN,TP]])
Check your results match with
my_confusion_matrix(df.actual_label.values, df.predicted_RF.values)
Instead of manually comparing, let’s verify that our functions worked using Python’s built in assert and numpy’s array_equal functions
assert np.array_equal(my_confusion_matrix(df.actual_label.values, df.predicted_RF.values), confusion_matrix(df.actual_label.values, df.predicted_RF.values) ), 'my_confusion_matrix() is not correct for RF'assert np.array_equal(my_confusion_matrix(df.actual_label.values, df.predicted_LR.values),confusion_matrix(df.actual_label.values, df.predicted_LR.values) ), 'my_confusion_matrix() is not correct for LR'
Given these four buckets (TP, FP, FN, TN), we can calculate many other performance metrics.
The most common metric for classification is accuracy, which is the fraction of samples predicted correctly as shown below:
We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels
from sklearn.metrics import accuracy_scoreaccuracy_score(df.actual_label.values, df.predicted_RF.values)
Your answer should be 0.6705165630156111
Define your own function that duplicates accuracy_score, using the formula above.
def my_accuracy_score(y_true, y_pred): # calculates the fraction of samples predicted correctly TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_accuracy_score(df.actual_label.values, df.predicted_RF.values) == accuracy_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_accuracy_score(df.actual_label.values, df.predicted_LR.values) == accuracy_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_RF.values)))print('Accuracy LR: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_LR.values)))
Using accuracy as a performance metric, the RF model is more accurate (0.67) than the LR model (0.62). So should we stop here and say RF model is the best model? No! Accuracy is not always the best metric to use to assess classification models. For example, let’s say that we are trying to predict something that only happens 1 out of 100 times. We could build a model that gets 99% accuracy by saying the event never happened. However, we catch 0% of the events we care about. The 0% measure here is another performance metric known as recall.
Recall (also known as sensitivity) is the fraction of positives events that you predicted correctly as shown below:
We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels
from sklearn.metrics import recall_scorerecall_score(df.actual_label.values, df.predicted_RF.values)
Define your own function that duplicates recall_score, using the formula above.
def my_recall_score(y_true, y_pred): # calculates the fraction of positive samples predicted correctly TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_recall_score(df.actual_label.values, df.predicted_RF.values) == recall_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_recall_score(df.actual_label.values, df.predicted_LR.values) == recall_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_RF.values)))print('Recall LR: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_LR.values)))
One method to boost the recall is to increase the number of samples that you define as predicted positive by lowering the threshold for predicted positive. Unfortunately, this will also increase the number of false positives. Another performance metric called precision takes this into account.
Precision is the fraction of predicted positives events that are actually positive as shown below:
We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels
from sklearn.metrics import precision_scoreprecision_score(df.actual_label.values, df.predicted_RF.values)
Define your own function that duplicates precision_score, using the formula above.
def my_precision_score(y_true, y_pred): # calculates the fraction of predicted positives samples that are actually positive TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_precision_score(df.actual_label.values, df.predicted_RF.values) == precision_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_precision_score(df.actual_label.values, df.predicted_LR.values) == precision_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_RF.values)))print('Precision LR: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_LR.values)))
In this case, it looks like RF model is better at both recall and precision. But what would you do if one model was better at recall and the other was better at precision. One method that some data scientists use is called the F1 score.
The f1 score is the harmonic mean of recall and precision, with a higher score as a better model. The f1 score is calculated using the following formula:
We can obtain the f1 score from scikit-learn, which takes as inputs the actual labels and the predicted labels
from sklearn.metrics import f1_scoref1_score(df.actual_label.values, df.predicted_RF.values)
Define your own function that duplicates f1_score, using the formula above.
def my_f1_score(y_true, y_pred): # calculates the F1 score recall = my_recall_score(y_true,y_pred) precision = my_precision_score(y_true,y_pred) return # your code hereassert my_f1_score(df.actual_label.values, df.predicted_RF.values) == f1_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_f1_score(df.actual_label.values, df.predicted_LR.values) == f1_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_RF.values)))print('F1 LR: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_LR.values)))
So far, we have assumed that we defined a threshold of 0.5 for selecting which samples are predicted as positive. If we change this threshold the performance metrics will change. As shown below:
print('scores with threshold = 0.5')print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_RF.values)))print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_RF.values)))print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_RF.values)))print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_RF.values)))print(' ')print('scores with threshold = 0.25')print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))
How do we assess a model if we haven’t picked a threshold? One very common method is using the receiver operating characteristic (ROC) curve.
ROC curves are VERY help with understanding the balance between true-positive rate and false positive rates. Sci-kit learn has built in functions for ROC curves and for analyzing them. The inputs to these functions (roc_curve and roc_auc_score) are the actual labels and the predicted probabilities (not the predicted labels). Both roc_curve and roc_auc_score are both complicated functions, so we will not have you write these functions from scratch. Instead, we will show you how to use sci-kit learn's functions and explain the key points. Let's begin by using roc_curve to make the ROC plot.
from sklearn.metrics import roc_curvefpr_RF, tpr_RF, thresholds_RF = roc_curve(df.actual_label.values, df.model_RF.values)fpr_LR, tpr_LR, thresholds_LR = roc_curve(df.actual_label.values, df.model_LR.values)
The roc_curve function returns three lists:
thresholds = all unique prediction probabilities in descending order
fpr = the false positive rate (FP / (FP + TN)) for each threshold
tpr = the true positive rate (TP / (TP + FN)) for each threshold
We can plot the ROC curve for each model as shown below.
import matplotlib.pyplot as pltplt.plot(fpr_RF, tpr_RF,'r-',label = 'RF')plt.plot(fpr_LR,tpr_LR,'b-', label= 'LR')plt.plot([0,1],[0,1],'k-',label='random')plt.plot([0,0,1,1],[0,1,1,1],'g-',label='perfect')plt.legend()plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()
There are a couple things that we can observer from this figure:
a model that randomly guesses the label will result in the black line and you want to have a model that has a curve above this black line
an ROC that is farther away from the black line is better, so RF (red) looks better than LR (blue)
Although not seen directly, a high threshold results in a point in the bottom left and a low threshold results in a point in the top right. This means as you decrease the threshold you get higher TPR at the cost of a higher FPR
To analyze the performance, we will use the area-under-curve metric.
from sklearn.metrics import roc_auc_scoreauc_RF = roc_auc_score(df.actual_label.values, df.model_RF.values)auc_LR = roc_auc_score(df.actual_label.values, df.model_LR.values)print('AUC RF:%.3f'% auc_RF)print('AUC LR:%.3f'% auc_LR)
As you can see, the area under the curve for the RF model (AUC = 0.738) is better than the LR (AUC = 0.666). When I plot the ROC curve, I like to add the AUC to the legend as shown below.
import matplotlib.pyplot as pltplt.plot(fpr_RF, tpr_RF,'r-',label = 'RF AUC: %.3f'%auc_RF)plt.plot(fpr_LR,tpr_LR,'b-', label= 'LR AUC: %.3f'%auc_LR)plt.plot([0,1],[0,1],'k-',label='random')plt.plot([0,0,1,1],[0,1,1,1],'g-',label='perfect')plt.legend()plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()
Overall, in this toy example the model RF wins with every performance metric.
In predictive analytics, when deciding between two models it is important to pick a single performance metric. As you can see here, there are many that you can choose from (accuracy, recall, precision, f1-score, AUC, etc). Ultimately, you should use the performance metric that is most suitable for the business problem at hand. Many data scientists prefer to use the AUC to analyze each model’s performance because it does not require selecting a threshold and helps balance true positive rate and false positive rate.
Please leave a comment if you have any suggestions how to improve this tutorial. | [
{
"code": null,
"e": 358,
"s": 171,
"text": "In this tutorial, we will walk through a few of the classifications metrics in Python’s scikit-learn and write our own functions from scratch to understand the math behind a few of them."
},
{
"code": null,
"e": 1002,
"s": 358,
"text": "One major area of predictive modeling in data science is classification. Classification consists of trying to predict which class a particular sample from a population comes from. For example, if we are trying to predict if a particular patient will be re-hospitalized, the two possible classes are hospital (positive) and not-hospitalized (negative). The classification model then tries to predict if each patient will be hospitalized or not hospitalized. In other words, classification is simply trying to predict which bucket (predicted positive vs predicted negative) a particular sample from the population should be placed as seen below."
},
{
"code": null,
"e": 1606,
"s": 1002,
"text": "As you train your classification predictive model, you will want to assess how good it is. Interestingly, there are many different ways of evaluating the performance. Most data scientists that use Python for predictive modeling use the Python package called scikit-learn. Scikit-learn contains many built-in functions for analyzing the performance of models. In this tutorial, we will walk through a few of these metrics and write our own functions from scratch to understand the math behind a few of them. If you would prefer to just read about performance metrics, please see my previous post at here."
},
{
"code": null,
"e": 1676,
"s": 1606,
"text": "This tutorial will cover the following metrics from sklearn.metrics :"
},
{
"code": null,
"e": 1693,
"s": 1676,
"text": "confusion_matrix"
},
{
"code": null,
"e": 1708,
"s": 1693,
"text": "accuracy_score"
},
{
"code": null,
"e": 1721,
"s": 1708,
"text": "recall_score"
},
{
"code": null,
"e": 1737,
"s": 1721,
"text": "precision_score"
},
{
"code": null,
"e": 1746,
"s": 1737,
"text": "f1_score"
},
{
"code": null,
"e": 1756,
"s": 1746,
"text": "roc_curve"
},
{
"code": null,
"e": 1770,
"s": 1756,
"text": "roc_auc_score"
},
{
"code": null,
"e": 1996,
"s": 1770,
"text": "For a sample dataset and jupyter notebook, please visit my github here. We will write our own functions from scratch assuming a two-class classification. Note that you will need to fill in the parts tagged as # your code here"
},
{
"code": null,
"e": 2201,
"s": 1996,
"text": "Let’s load a sample data set that has the actual labels (actual_label) and the prediction probabilities for two models (model_RF and model_LR). Here the probabilities are the probability of being class 1."
},
{
"code": null,
"e": 2258,
"s": 2201,
"text": "import pandas as pddf = pd.read_csv('data.csv')df.head()"
},
{
"code": null,
"e": 2543,
"s": 2258,
"text": "In most data science projects, you will define a threshold to define which prediction probabilities are labeled as predicted positive vs predicted negative. For now let’s assume the threshold is 0.5. Let’s add two additional columns that convert the probabilities to predicted labels."
},
{
"code": null,
"e": 2675,
"s": 2543,
"text": "thresh = 0.5df['predicted_RF'] = (df.model_RF >= 0.5).astype('int')df['predicted_LR'] = (df.model_LR >= 0.5).astype('int')df.head()"
},
{
"code": null,
"e": 2782,
"s": 2675,
"text": "Given an actual label and a predicted label, the first thing we can do is divide our samples in 4 buckets:"
},
{
"code": null,
"e": 2824,
"s": 2782,
"text": "True positive — actual = 1, predicted = 1"
},
{
"code": null,
"e": 2867,
"s": 2824,
"text": "False positive — actual = 0, predicted = 1"
},
{
"code": null,
"e": 2910,
"s": 2867,
"text": "False negative — actual = 1, predicted = 0"
},
{
"code": null,
"e": 2952,
"s": 2910,
"text": "True negative — actual = 0, predicted = 0"
},
{
"code": null,
"e": 3179,
"s": 2952,
"text": "These buckets can be represented with the following image (original source https://en.wikipedia.org/wiki/Precision_and_recall#/media/File:Precisionrecall.svg) and we will reference this image in many of the calculations below."
},
{
"code": null,
"e": 3256,
"s": 3179,
"text": "These buckets can also be displayed using a confusion matrix as shown below:"
},
{
"code": null,
"e": 3392,
"s": 3256,
"text": "We can obtain the confusion matrix (as a 2x2 array) from scikit-learn, which takes as inputs the actual labels and the predicted labels"
},
{
"code": null,
"e": 3501,
"s": 3392,
"text": "from sklearn.metrics import confusion_matrixconfusion_matrix(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 3739,
"s": 3501,
"text": "where there were 5047 true positives, 2360 false positives, 2832 false negatives and 5519 true negatives. Let’s define our own functions to verify confusion_matrix. Note that I filled in the first one and you need to fill in the other 3."
},
{
"code": null,
"e": 4244,
"s": 3739,
"text": "def find_TP(y_true, y_pred): # counts the number of true positives (y_true = 1, y_pred = 1) return sum((y_true == 1) & (y_pred == 1))def find_FN(y_true, y_pred): # counts the number of false negatives (y_true = 1, y_pred = 0) return # your code heredef find_FP(y_true, y_pred): # counts the number of false positives (y_true = 0, y_pred = 1) return # your code heredef find_TN(y_true, y_pred): # counts the number of true negatives (y_true = 0, y_pred = 0) return # your code here"
},
{
"code": null,
"e": 4282,
"s": 4244,
"text": "You can check your results match with"
},
{
"code": null,
"e": 4555,
"s": 4282,
"text": "print('TP:',find_TP(df.actual_label.values, df.predicted_RF.values))print('FN:',find_FN(df.actual_label.values, df.predicted_RF.values))print('FP:',find_FP(df.actual_label.values, df.predicted_RF.values))print('TN:',find_TN(df.actual_label.values, df.predicted_RF.values))"
},
{
"code": null,
"e": 4675,
"s": 4555,
"text": "Let’s write a function that will calculate all four of these for us, and another function to duplicate confusion_matrix"
},
{
"code": null,
"e": 5047,
"s": 4675,
"text": "import numpy as npdef find_conf_matrix_values(y_true,y_pred): # calculate TP, FN, FP, TN TP = find_TP(y_true,y_pred) FN = find_FN(y_true,y_pred) FP = find_FP(y_true,y_pred) TN = find_TN(y_true,y_pred) return TP,FN,FP,TNdef my_confusion_matrix(y_true, y_pred): TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return np.array([[TN,FP],[FN,TP]])"
},
{
"code": null,
"e": 5077,
"s": 5047,
"text": "Check your results match with"
},
{
"code": null,
"e": 5145,
"s": 5077,
"text": "my_confusion_matrix(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 5280,
"s": 5145,
"text": "Instead of manually comparing, let’s verify that our functions worked using Python’s built in assert and numpy’s array_equal functions"
},
{
"code": null,
"e": 5690,
"s": 5280,
"text": "assert np.array_equal(my_confusion_matrix(df.actual_label.values, df.predicted_RF.values), confusion_matrix(df.actual_label.values, df.predicted_RF.values) ), 'my_confusion_matrix() is not correct for RF'assert np.array_equal(my_confusion_matrix(df.actual_label.values, df.predicted_LR.values),confusion_matrix(df.actual_label.values, df.predicted_LR.values) ), 'my_confusion_matrix() is not correct for LR'"
},
{
"code": null,
"e": 5782,
"s": 5690,
"text": "Given these four buckets (TP, FP, FN, TN), we can calculate many other performance metrics."
},
{
"code": null,
"e": 5906,
"s": 5782,
"text": "The most common metric for classification is accuracy, which is the fraction of samples predicted correctly as shown below:"
},
{
"code": null,
"e": 6023,
"s": 5906,
"text": "We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels"
},
{
"code": null,
"e": 6128,
"s": 6023,
"text": "from sklearn.metrics import accuracy_scoreaccuracy_score(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 6169,
"s": 6128,
"text": "Your answer should be 0.6705165630156111"
},
{
"code": null,
"e": 6251,
"s": 6169,
"text": "Define your own function that duplicates accuracy_score, using the formula above."
},
{
"code": null,
"e": 6967,
"s": 6251,
"text": "def my_accuracy_score(y_true, y_pred): # calculates the fraction of samples predicted correctly TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_accuracy_score(df.actual_label.values, df.predicted_RF.values) == accuracy_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_accuracy_score(df.actual_label.values, df.predicted_LR.values) == accuracy_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_RF.values)))print('Accuracy LR: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_LR.values)))"
},
{
"code": null,
"e": 7512,
"s": 6967,
"text": "Using accuracy as a performance metric, the RF model is more accurate (0.67) than the LR model (0.62). So should we stop here and say RF model is the best model? No! Accuracy is not always the best metric to use to assess classification models. For example, let’s say that we are trying to predict something that only happens 1 out of 100 times. We could build a model that gets 99% accuracy by saying the event never happened. However, we catch 0% of the events we care about. The 0% measure here is another performance metric known as recall."
},
{
"code": null,
"e": 7628,
"s": 7512,
"text": "Recall (also known as sensitivity) is the fraction of positives events that you predicted correctly as shown below:"
},
{
"code": null,
"e": 7745,
"s": 7628,
"text": "We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels"
},
{
"code": null,
"e": 7846,
"s": 7745,
"text": "from sklearn.metrics import recall_scorerecall_score(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 7926,
"s": 7846,
"text": "Define your own function that duplicates recall_score, using the formula above."
},
{
"code": null,
"e": 8633,
"s": 7926,
"text": "def my_recall_score(y_true, y_pred): # calculates the fraction of positive samples predicted correctly TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_recall_score(df.actual_label.values, df.predicted_RF.values) == recall_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_recall_score(df.actual_label.values, df.predicted_LR.values) == recall_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_RF.values)))print('Recall LR: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_LR.values)))"
},
{
"code": null,
"e": 8928,
"s": 8633,
"text": "One method to boost the recall is to increase the number of samples that you define as predicted positive by lowering the threshold for predicted positive. Unfortunately, this will also increase the number of false positives. Another performance metric called precision takes this into account."
},
{
"code": null,
"e": 9027,
"s": 8928,
"text": "Precision is the fraction of predicted positives events that are actually positive as shown below:"
},
{
"code": null,
"e": 9144,
"s": 9027,
"text": "We can obtain the accuracy score from scikit-learn, which takes as inputs the actual labels and the predicted labels"
},
{
"code": null,
"e": 9251,
"s": 9144,
"text": "from sklearn.metrics import precision_scoreprecision_score(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 9334,
"s": 9251,
"text": "Define your own function that duplicates precision_score, using the formula above."
},
{
"code": null,
"e": 10086,
"s": 9334,
"text": "def my_precision_score(y_true, y_pred): # calculates the fraction of predicted positives samples that are actually positive TP,FN,FP,TN = find_conf_matrix_values(y_true,y_pred) return # your code hereassert my_precision_score(df.actual_label.values, df.predicted_RF.values) == precision_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_precision_score(df.actual_label.values, df.predicted_LR.values) == precision_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_RF.values)))print('Precision LR: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_LR.values)))"
},
{
"code": null,
"e": 10323,
"s": 10086,
"text": "In this case, it looks like RF model is better at both recall and precision. But what would you do if one model was better at recall and the other was better at precision. One method that some data scientists use is called the F1 score."
},
{
"code": null,
"e": 10477,
"s": 10323,
"text": "The f1 score is the harmonic mean of recall and precision, with a higher score as a better model. The f1 score is calculated using the following formula:"
},
{
"code": null,
"e": 10588,
"s": 10477,
"text": "We can obtain the f1 score from scikit-learn, which takes as inputs the actual labels and the predicted labels"
},
{
"code": null,
"e": 10681,
"s": 10588,
"text": "from sklearn.metrics import f1_scoref1_score(df.actual_label.values, df.predicted_RF.values)"
},
{
"code": null,
"e": 10757,
"s": 10681,
"text": "Define your own function that duplicates f1_score, using the formula above."
},
{
"code": null,
"e": 11426,
"s": 10757,
"text": "def my_f1_score(y_true, y_pred): # calculates the F1 score recall = my_recall_score(y_true,y_pred) precision = my_precision_score(y_true,y_pred) return # your code hereassert my_f1_score(df.actual_label.values, df.predicted_RF.values) == f1_score(df.actual_label.values, df.predicted_RF.values), 'my_accuracy_score failed on RF'assert my_f1_score(df.actual_label.values, df.predicted_LR.values) == f1_score(df.actual_label.values, df.predicted_LR.values), 'my_accuracy_score failed on LR'print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_RF.values)))print('F1 LR: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_LR.values)))"
},
{
"code": null,
"e": 11621,
"s": 11426,
"text": "So far, we have assumed that we defined a threshold of 0.5 for selecting which samples are predicted as positive. If we change this threshold the performance metrics will change. As shown below:"
},
{
"code": null,
"e": 12509,
"s": 11621,
"text": "print('scores with threshold = 0.5')print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, df.predicted_RF.values)))print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, df.predicted_RF.values)))print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, df.predicted_RF.values)))print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, df.predicted_RF.values)))print(' ')print('scores with threshold = 0.25')print('Accuracy RF: %.3f'%(my_accuracy_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('Recall RF: %.3f'%(my_recall_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('Precision RF: %.3f'%(my_precision_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))print('F1 RF: %.3f'%(my_f1_score(df.actual_label.values, (df.model_RF >= 0.25).astype('int').values)))"
},
{
"code": null,
"e": 12651,
"s": 12509,
"text": "How do we assess a model if we haven’t picked a threshold? One very common method is using the receiver operating characteristic (ROC) curve."
},
{
"code": null,
"e": 13247,
"s": 12651,
"text": "ROC curves are VERY help with understanding the balance between true-positive rate and false positive rates. Sci-kit learn has built in functions for ROC curves and for analyzing them. The inputs to these functions (roc_curve and roc_auc_score) are the actual labels and the predicted probabilities (not the predicted labels). Both roc_curve and roc_auc_score are both complicated functions, so we will not have you write these functions from scratch. Instead, we will show you how to use sci-kit learn's functions and explain the key points. Let's begin by using roc_curve to make the ROC plot."
},
{
"code": null,
"e": 13455,
"s": 13247,
"text": "from sklearn.metrics import roc_curvefpr_RF, tpr_RF, thresholds_RF = roc_curve(df.actual_label.values, df.model_RF.values)fpr_LR, tpr_LR, thresholds_LR = roc_curve(df.actual_label.values, df.model_LR.values)"
},
{
"code": null,
"e": 13499,
"s": 13455,
"text": "The roc_curve function returns three lists:"
},
{
"code": null,
"e": 13568,
"s": 13499,
"text": "thresholds = all unique prediction probabilities in descending order"
},
{
"code": null,
"e": 13634,
"s": 13568,
"text": "fpr = the false positive rate (FP / (FP + TN)) for each threshold"
},
{
"code": null,
"e": 13699,
"s": 13634,
"text": "tpr = the true positive rate (TP / (TP + FN)) for each threshold"
},
{
"code": null,
"e": 13756,
"s": 13699,
"text": "We can plot the ROC curve for each model as shown below."
},
{
"code": null,
"e": 14049,
"s": 13756,
"text": "import matplotlib.pyplot as pltplt.plot(fpr_RF, tpr_RF,'r-',label = 'RF')plt.plot(fpr_LR,tpr_LR,'b-', label= 'LR')plt.plot([0,1],[0,1],'k-',label='random')plt.plot([0,0,1,1],[0,1,1,1],'g-',label='perfect')plt.legend()plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()"
},
{
"code": null,
"e": 14114,
"s": 14049,
"text": "There are a couple things that we can observer from this figure:"
},
{
"code": null,
"e": 14252,
"s": 14114,
"text": "a model that randomly guesses the label will result in the black line and you want to have a model that has a curve above this black line"
},
{
"code": null,
"e": 14351,
"s": 14252,
"text": "an ROC that is farther away from the black line is better, so RF (red) looks better than LR (blue)"
},
{
"code": null,
"e": 14579,
"s": 14351,
"text": "Although not seen directly, a high threshold results in a point in the bottom left and a low threshold results in a point in the top right. This means as you decrease the threshold you get higher TPR at the cost of a higher FPR"
},
{
"code": null,
"e": 14648,
"s": 14579,
"text": "To analyze the performance, we will use the area-under-curve metric."
},
{
"code": null,
"e": 14878,
"s": 14648,
"text": "from sklearn.metrics import roc_auc_scoreauc_RF = roc_auc_score(df.actual_label.values, df.model_RF.values)auc_LR = roc_auc_score(df.actual_label.values, df.model_LR.values)print('AUC RF:%.3f'% auc_RF)print('AUC LR:%.3f'% auc_LR)"
},
{
"code": null,
"e": 15066,
"s": 14878,
"text": "As you can see, the area under the curve for the RF model (AUC = 0.738) is better than the LR (AUC = 0.666). When I plot the ROC curve, I like to add the AUC to the legend as shown below."
},
{
"code": null,
"e": 15393,
"s": 15066,
"text": "import matplotlib.pyplot as pltplt.plot(fpr_RF, tpr_RF,'r-',label = 'RF AUC: %.3f'%auc_RF)plt.plot(fpr_LR,tpr_LR,'b-', label= 'LR AUC: %.3f'%auc_LR)plt.plot([0,1],[0,1],'k-',label='random')plt.plot([0,0,1,1],[0,1,1,1],'g-',label='perfect')plt.legend()plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()"
},
{
"code": null,
"e": 15471,
"s": 15393,
"text": "Overall, in this toy example the model RF wins with every performance metric."
},
{
"code": null,
"e": 15991,
"s": 15471,
"text": "In predictive analytics, when deciding between two models it is important to pick a single performance metric. As you can see here, there are many that you can choose from (accuracy, recall, precision, f1-score, AUC, etc). Ultimately, you should use the performance metric that is most suitable for the business problem at hand. Many data scientists prefer to use the AUC to analyze each model’s performance because it does not require selecting a threshold and helps balance true positive rate and false positive rate."
}
]
|
10 Python File System Methods You Should Know | by Jeff Hale | Towards Data Science | You can write Python programs to interact with the file system to do cool stuff. How to do so isn’t always super clear.
This article is a guide for current and aspiring developers and data scientists. We’ll highlight 10 essential os and shutil commands so you can write scripts to automate interactions with the file system.
The file system is a bit like a house. Say you’re spring cleaning and you need to move boxes of notebooks from one room to another.
The boxes are like directories. They hold things. In this case, notebooks.
The notebooks are like files. You can read and write to them. You can put them in your directory boxes.
Capiche?
In this guide we’ll look at methods from the os and shutil modules. The os module is the primary Python module for interacting with the operating system. The shutil module also contains high-level file operations. For some reason you make directories with os but move and copy them with shutil. Go figure. 😏
In Python 3.4 the pathlib module was added to the standard library to improve working with file paths, and as of 3.6 is plays nicely with the rest of the standard library. The pathlib methods provide some benefits for parsing file paths over the methods we’ll discuss below — namely pathlib treats paths as objects rather than strings. Although pathlib is handy, it doesn’t have all the lower level functionality we’ll be exploring. Also, you’ll undoubtedly see the os and shutil methods below in code for years to come. So it’s definitely a good idea to be familiar with them.
I plan to discuss pathlib in a future article, so follow me to make sure you don’t miss it. To learn more about the pathlib module now, see this article and this article.
A few other things to know before we dig in:
This guide is designed for Python 3. Python 2 won’t be supported beyond Jan. 1, 2020.
You need to import os and shutil into your file to use these commands.
My example code is available on GitHub.
Substitute your own arguments for the arguments in quotes below.
Now that we’ve got the context out of the way, let’s get to it! Here’s the list of 10 commands you should know.
The list below follows this pattern:
Method — Description — Equivalent macOS Shell Command
os.getcwd() — get the current working directory path as a string — pwd
os.listdir() — get the contents of the current working directory as a list of strings — ls
os.walk("starting_directory_path")— returns a generator with name and path info for directories and files in the the current directory and all subdirectories— no exact short CLI equivalent, but ls -R provides subdirectory names and the names of files within subdirectories
os.chdir("/absolute/or/relative/path") — change the current working directory — cd
os.path.join()—create a path for later use — no short CLI equivalent
os.makedirs("dir1/dir2") — make directory —mkdir -p
shutil.copy2("source_file_path", "destination_directory_path") — copy a file or directory — cp
shutil.move("source_file_path", "destination_directory_path") — move a file or directory — mv
os.remove("my_file_path") — remove a file — rm
shutil.rmtree("my_directory_path")— remove a directory and all files and directories in it —rm -rf
Let’s discuss.
os.getcwd()
os.getcwd() returns the current working directory as a string. 😄
os.listdir()
os.listdir() returns the contents of the current working directory as a list of strings. 😄
os.walk("my_start_directory")
os.walk() creates a generator that can return information about the current directory and subdirectories. It works through the directories in the specified starting directory.
os.walk() returns the following items for each directory it traverses:
current directory path as a stringsubdirectory names in the current directory as lists of stringsfilenames in current directory as a list of strings
current directory path as a string
subdirectory names in the current directory as lists of strings
filenames in current directory as a list of strings
It does this for each directory!
It’s often useful to use os.walk() with a for loop to iterate over the contents of a directory and its subdirectories. For example, the following code will print all files in the directories and subdirectories of the current working directory.
import oscwd = os.getcwd()for dir_path, dir_names, file_names in os.walk(cwd): for f in file_names: print(f)
That’s how we get info, now let’s look at commands that change the working directory or move, copy, or delete parts of the file system.
os.chdir("/absolute/or/relative/path")
This method changes the current working directory to either the absolute or relative path provided.
If your code then makes other changes to the file system, it’s a good idea to handle any exceptions raised when using this method with try-except. Otherwise you might be deleting directories or files you don’t want deleted. 😢
os.path.join()
The os.path module has a number of useful methods for common pathname manipulations. You can use it to find information about directory names and parts of directory names. The module also has methods to check whether a file or directory exists.
os.path.join() is designed to create a path that will work on most any operating system by joining multiple strings into one beautiful file path.😄
Here’s the description from the docs:
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last...
Basically, if you are on a Unix or macOS system, os.path.join() sticks a forward slash (“/”) between each string you provide to create a path. If the operating system needs a “\” instead, then join knows to use a back slash.
os.path.join() also provides clear information to other developers that you are creating a path. Definitely use it instead of manual string concatenation to avoid looking like a rookie. 😉
os.makedirs("dir1/dir2")
os.makedirs() makes directories. The mkdir() method also makes directories, but it does not make intermediate directories. So I suggest you use os.makedirs().
shutil.copy2("source_file", "destination")
There are many ways to copy files and directories in Python. shutil.copy2() is a good choice because it tries to preserve as much of the source file’s metadata as possible. For more discussion, see this article.
shutil.move("source_file", "destination")
Use shutil.move() to change a file’s location. It uses copy2 as the default under the hood.
os.remove("my_file_path")
Sometimes you need to remove a file. os.remove() is your tool.
shutil.rmtree("my_directory_path")
shutil.rmtree() removes a directory and all files and directories in it.
Careful with functions that delete things! You may want to print what will be deleted as a dry run with print(). Then run substitute in your remove function for print() when you’re sure it won’t delete the wrong files. Hat tip to Al Sweigart for that idea in Automate the Boring Stuff with Python.
Here’s the full list one more time.
The list below follows this pattern: Method— Description — Equivalent macOS Shell Command
os.getcwd() — get the current working directory path as a string — pwd
os.listdir() — get the contents of the current working directory as a list of strings — ls
os.walk("starting_directory_path")— returns a generator with name and path info for directories and files in the the current directory and all subdirectories — no exact short CLI equivalent, but ls -R provides subdirectory names and the names of files within subdirectories
os.chdir("/absolute/or/relative/path") — change the current working directory — cd
os.path.join()—create a path for later use — no short CLI equivalent
os.makedirs("dir1/dir2") — make directory —mkdir-p
shutil.copy2("source_file_path", "destination_directory_path") — copy a file or directory — cp
shutil.move("source_file_path", "destination_directory_path") — move a file or directory — mv
os.remove("my_file_path") — remove a file — rm
shutil.rmtree("my_directory_path")— remove a directory and all files and directories in it —rm -rf
Now you’ve seen the basics of interacting with the file system in Python. Try these commands in your IPython interpreter for quick feedback. Then explain them to someone else to solidify your knowledge. You’ll be less sore than if you had moved boxes of notebooks around your house. 🏠 But the exercise would have been good, so now you can hit the gym instead. 🏋️♀️😉
If you want to learn about reading and writing from files with Python check out the open function. Remember to use a context manager like so: with open(‘myfile’) as file: .😄
I hope you found this intro to Python file system manipulation useful. If you did, please share it on your favorite social media channels so others can find it too.
I write about Python, Docker, data science, and more. If any of that’s of interest to you, read more here and follow me on Medium.
Thanks for reading! 👏 | [
{
"code": null,
"e": 292,
"s": 172,
"text": "You can write Python programs to interact with the file system to do cool stuff. How to do so isn’t always super clear."
},
{
"code": null,
"e": 497,
"s": 292,
"text": "This article is a guide for current and aspiring developers and data scientists. We’ll highlight 10 essential os and shutil commands so you can write scripts to automate interactions with the file system."
},
{
"code": null,
"e": 629,
"s": 497,
"text": "The file system is a bit like a house. Say you’re spring cleaning and you need to move boxes of notebooks from one room to another."
},
{
"code": null,
"e": 704,
"s": 629,
"text": "The boxes are like directories. They hold things. In this case, notebooks."
},
{
"code": null,
"e": 808,
"s": 704,
"text": "The notebooks are like files. You can read and write to them. You can put them in your directory boxes."
},
{
"code": null,
"e": 817,
"s": 808,
"text": "Capiche?"
},
{
"code": null,
"e": 1125,
"s": 817,
"text": "In this guide we’ll look at methods from the os and shutil modules. The os module is the primary Python module for interacting with the operating system. The shutil module also contains high-level file operations. For some reason you make directories with os but move and copy them with shutil. Go figure. 😏"
},
{
"code": null,
"e": 1703,
"s": 1125,
"text": "In Python 3.4 the pathlib module was added to the standard library to improve working with file paths, and as of 3.6 is plays nicely with the rest of the standard library. The pathlib methods provide some benefits for parsing file paths over the methods we’ll discuss below — namely pathlib treats paths as objects rather than strings. Although pathlib is handy, it doesn’t have all the lower level functionality we’ll be exploring. Also, you’ll undoubtedly see the os and shutil methods below in code for years to come. So it’s definitely a good idea to be familiar with them."
},
{
"code": null,
"e": 1874,
"s": 1703,
"text": "I plan to discuss pathlib in a future article, so follow me to make sure you don’t miss it. To learn more about the pathlib module now, see this article and this article."
},
{
"code": null,
"e": 1919,
"s": 1874,
"text": "A few other things to know before we dig in:"
},
{
"code": null,
"e": 2005,
"s": 1919,
"text": "This guide is designed for Python 3. Python 2 won’t be supported beyond Jan. 1, 2020."
},
{
"code": null,
"e": 2076,
"s": 2005,
"text": "You need to import os and shutil into your file to use these commands."
},
{
"code": null,
"e": 2116,
"s": 2076,
"text": "My example code is available on GitHub."
},
{
"code": null,
"e": 2181,
"s": 2116,
"text": "Substitute your own arguments for the arguments in quotes below."
},
{
"code": null,
"e": 2293,
"s": 2181,
"text": "Now that we’ve got the context out of the way, let’s get to it! Here’s the list of 10 commands you should know."
},
{
"code": null,
"e": 2330,
"s": 2293,
"text": "The list below follows this pattern:"
},
{
"code": null,
"e": 2384,
"s": 2330,
"text": "Method — Description — Equivalent macOS Shell Command"
},
{
"code": null,
"e": 2455,
"s": 2384,
"text": "os.getcwd() — get the current working directory path as a string — pwd"
},
{
"code": null,
"e": 2546,
"s": 2455,
"text": "os.listdir() — get the contents of the current working directory as a list of strings — ls"
},
{
"code": null,
"e": 2819,
"s": 2546,
"text": "os.walk(\"starting_directory_path\")— returns a generator with name and path info for directories and files in the the current directory and all subdirectories— no exact short CLI equivalent, but ls -R provides subdirectory names and the names of files within subdirectories"
},
{
"code": null,
"e": 2902,
"s": 2819,
"text": "os.chdir(\"/absolute/or/relative/path\") — change the current working directory — cd"
},
{
"code": null,
"e": 2971,
"s": 2902,
"text": "os.path.join()—create a path for later use — no short CLI equivalent"
},
{
"code": null,
"e": 3023,
"s": 2971,
"text": "os.makedirs(\"dir1/dir2\") — make directory —mkdir -p"
},
{
"code": null,
"e": 3118,
"s": 3023,
"text": "shutil.copy2(\"source_file_path\", \"destination_directory_path\") — copy a file or directory — cp"
},
{
"code": null,
"e": 3212,
"s": 3118,
"text": "shutil.move(\"source_file_path\", \"destination_directory_path\") — move a file or directory — mv"
},
{
"code": null,
"e": 3259,
"s": 3212,
"text": "os.remove(\"my_file_path\") — remove a file — rm"
},
{
"code": null,
"e": 3358,
"s": 3259,
"text": "shutil.rmtree(\"my_directory_path\")— remove a directory and all files and directories in it —rm -rf"
},
{
"code": null,
"e": 3373,
"s": 3358,
"text": "Let’s discuss."
},
{
"code": null,
"e": 3385,
"s": 3373,
"text": "os.getcwd()"
},
{
"code": null,
"e": 3450,
"s": 3385,
"text": "os.getcwd() returns the current working directory as a string. 😄"
},
{
"code": null,
"e": 3463,
"s": 3450,
"text": "os.listdir()"
},
{
"code": null,
"e": 3554,
"s": 3463,
"text": "os.listdir() returns the contents of the current working directory as a list of strings. 😄"
},
{
"code": null,
"e": 3584,
"s": 3554,
"text": "os.walk(\"my_start_directory\")"
},
{
"code": null,
"e": 3760,
"s": 3584,
"text": "os.walk() creates a generator that can return information about the current directory and subdirectories. It works through the directories in the specified starting directory."
},
{
"code": null,
"e": 3831,
"s": 3760,
"text": "os.walk() returns the following items for each directory it traverses:"
},
{
"code": null,
"e": 3980,
"s": 3831,
"text": "current directory path as a stringsubdirectory names in the current directory as lists of stringsfilenames in current directory as a list of strings"
},
{
"code": null,
"e": 4015,
"s": 3980,
"text": "current directory path as a string"
},
{
"code": null,
"e": 4079,
"s": 4015,
"text": "subdirectory names in the current directory as lists of strings"
},
{
"code": null,
"e": 4131,
"s": 4079,
"text": "filenames in current directory as a list of strings"
},
{
"code": null,
"e": 4164,
"s": 4131,
"text": "It does this for each directory!"
},
{
"code": null,
"e": 4408,
"s": 4164,
"text": "It’s often useful to use os.walk() with a for loop to iterate over the contents of a directory and its subdirectories. For example, the following code will print all files in the directories and subdirectories of the current working directory."
},
{
"code": null,
"e": 4527,
"s": 4408,
"text": "import oscwd = os.getcwd()for dir_path, dir_names, file_names in os.walk(cwd): for f in file_names: print(f)"
},
{
"code": null,
"e": 4663,
"s": 4527,
"text": "That’s how we get info, now let’s look at commands that change the working directory or move, copy, or delete parts of the file system."
},
{
"code": null,
"e": 4702,
"s": 4663,
"text": "os.chdir(\"/absolute/or/relative/path\")"
},
{
"code": null,
"e": 4802,
"s": 4702,
"text": "This method changes the current working directory to either the absolute or relative path provided."
},
{
"code": null,
"e": 5028,
"s": 4802,
"text": "If your code then makes other changes to the file system, it’s a good idea to handle any exceptions raised when using this method with try-except. Otherwise you might be deleting directories or files you don’t want deleted. 😢"
},
{
"code": null,
"e": 5043,
"s": 5028,
"text": "os.path.join()"
},
{
"code": null,
"e": 5288,
"s": 5043,
"text": "The os.path module has a number of useful methods for common pathname manipulations. You can use it to find information about directory names and parts of directory names. The module also has methods to check whether a file or directory exists."
},
{
"code": null,
"e": 5435,
"s": 5288,
"text": "os.path.join() is designed to create a path that will work on most any operating system by joining multiple strings into one beautiful file path.😄"
},
{
"code": null,
"e": 5473,
"s": 5435,
"text": "Here’s the description from the docs:"
},
{
"code": null,
"e": 5688,
"s": 5473,
"text": "Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last..."
},
{
"code": null,
"e": 5913,
"s": 5688,
"text": "Basically, if you are on a Unix or macOS system, os.path.join() sticks a forward slash (“/”) between each string you provide to create a path. If the operating system needs a “\\” instead, then join knows to use a back slash."
},
{
"code": null,
"e": 6101,
"s": 5913,
"text": "os.path.join() also provides clear information to other developers that you are creating a path. Definitely use it instead of manual string concatenation to avoid looking like a rookie. 😉"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "os.makedirs(\"dir1/dir2\")"
},
{
"code": null,
"e": 6285,
"s": 6126,
"text": "os.makedirs() makes directories. The mkdir() method also makes directories, but it does not make intermediate directories. So I suggest you use os.makedirs()."
},
{
"code": null,
"e": 6328,
"s": 6285,
"text": "shutil.copy2(\"source_file\", \"destination\")"
},
{
"code": null,
"e": 6540,
"s": 6328,
"text": "There are many ways to copy files and directories in Python. shutil.copy2() is a good choice because it tries to preserve as much of the source file’s metadata as possible. For more discussion, see this article."
},
{
"code": null,
"e": 6582,
"s": 6540,
"text": "shutil.move(\"source_file\", \"destination\")"
},
{
"code": null,
"e": 6674,
"s": 6582,
"text": "Use shutil.move() to change a file’s location. It uses copy2 as the default under the hood."
},
{
"code": null,
"e": 6700,
"s": 6674,
"text": "os.remove(\"my_file_path\")"
},
{
"code": null,
"e": 6763,
"s": 6700,
"text": "Sometimes you need to remove a file. os.remove() is your tool."
},
{
"code": null,
"e": 6798,
"s": 6763,
"text": "shutil.rmtree(\"my_directory_path\")"
},
{
"code": null,
"e": 6871,
"s": 6798,
"text": "shutil.rmtree() removes a directory and all files and directories in it."
},
{
"code": null,
"e": 7169,
"s": 6871,
"text": "Careful with functions that delete things! You may want to print what will be deleted as a dry run with print(). Then run substitute in your remove function for print() when you’re sure it won’t delete the wrong files. Hat tip to Al Sweigart for that idea in Automate the Boring Stuff with Python."
},
{
"code": null,
"e": 7205,
"s": 7169,
"text": "Here’s the full list one more time."
},
{
"code": null,
"e": 7295,
"s": 7205,
"text": "The list below follows this pattern: Method— Description — Equivalent macOS Shell Command"
},
{
"code": null,
"e": 7366,
"s": 7295,
"text": "os.getcwd() — get the current working directory path as a string — pwd"
},
{
"code": null,
"e": 7457,
"s": 7366,
"text": "os.listdir() — get the contents of the current working directory as a list of strings — ls"
},
{
"code": null,
"e": 7731,
"s": 7457,
"text": "os.walk(\"starting_directory_path\")— returns a generator with name and path info for directories and files in the the current directory and all subdirectories — no exact short CLI equivalent, but ls -R provides subdirectory names and the names of files within subdirectories"
},
{
"code": null,
"e": 7814,
"s": 7731,
"text": "os.chdir(\"/absolute/or/relative/path\") — change the current working directory — cd"
},
{
"code": null,
"e": 7883,
"s": 7814,
"text": "os.path.join()—create a path for later use — no short CLI equivalent"
},
{
"code": null,
"e": 7934,
"s": 7883,
"text": "os.makedirs(\"dir1/dir2\") — make directory —mkdir-p"
},
{
"code": null,
"e": 8029,
"s": 7934,
"text": "shutil.copy2(\"source_file_path\", \"destination_directory_path\") — copy a file or directory — cp"
},
{
"code": null,
"e": 8123,
"s": 8029,
"text": "shutil.move(\"source_file_path\", \"destination_directory_path\") — move a file or directory — mv"
},
{
"code": null,
"e": 8170,
"s": 8123,
"text": "os.remove(\"my_file_path\") — remove a file — rm"
},
{
"code": null,
"e": 8269,
"s": 8170,
"text": "shutil.rmtree(\"my_directory_path\")— remove a directory and all files and directories in it —rm -rf"
},
{
"code": null,
"e": 8636,
"s": 8269,
"text": "Now you’ve seen the basics of interacting with the file system in Python. Try these commands in your IPython interpreter for quick feedback. Then explain them to someone else to solidify your knowledge. You’ll be less sore than if you had moved boxes of notebooks around your house. 🏠 But the exercise would have been good, so now you can hit the gym instead. 🏋️♀️😉"
},
{
"code": null,
"e": 8810,
"s": 8636,
"text": "If you want to learn about reading and writing from files with Python check out the open function. Remember to use a context manager like so: with open(‘myfile’) as file: .😄"
},
{
"code": null,
"e": 8975,
"s": 8810,
"text": "I hope you found this intro to Python file system manipulation useful. If you did, please share it on your favorite social media channels so others can find it too."
},
{
"code": null,
"e": 9106,
"s": 8975,
"text": "I write about Python, Docker, data science, and more. If any of that’s of interest to you, read more here and follow me on Medium."
}
]
|
Unix / Linux - Shell Substitution | The shell performs substitution when it encounters an expression that contains one or more special characters.
Here, the printing value of the variable is substituted by its value. Same time, "\n" is substituted by a new line −
#!/bin/sh
a=10
echo -e "Value of a is $a \n"
You will receive the following result. Here the -e option enables the interpretation of backslash escapes.
Value of a is 10
Following is the result without -e option −
Value of a is 10\n
The following escape sequences which can be used in echo command −
\\
backslash
\a
alert (BEL)
\b
backspace
\c
suppress trailing newline
\f
form feed
\n
new line
\r
carriage return
\t
horizontal tab
\v
vertical tab
You can use the -E option to disable the interpretation of the backslash escapes (default).
You can use the -n option to disable the insertion of a new line.
Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.
The command substitution is performed when a command is given as −
`command`
When performing the command substitution make sure that you use the backquote, not the single quote character.
Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrates the command substitution −
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
Upon execution, you will receive the following result −
Date is Thu Jul 2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul 2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15
Variable substitution enables the shell programmer to manipulate the value of a variable based on its state.
Here is the following table for all the possible substitutions −
${var}
Substitute the value of var.
${var:-word}
If var is null or unset, word is substituted for var. The value of var does not change.
${var:=word}
If var is null or unset, var is set to the value of word.
${var:?message}
If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
${var:+word}
If var is set, word is substituted for var. The value of var does not change.
Following is the example to show various states of the above substitution −
#!/bin/sh
echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"
echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"
Upon execution, you will receive the following result −
Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2858,
"s": 2747,
"text": "The shell performs substitution when it encounters an expression that contains one or more special characters."
},
{
"code": null,
"e": 2975,
"s": 2858,
"text": "Here, the printing value of the variable is substituted by its value. Same time, \"\\n\" is substituted by a new line −"
},
{
"code": null,
"e": 3021,
"s": 2975,
"text": "#!/bin/sh\n\na=10\necho -e \"Value of a is $a \\n\""
},
{
"code": null,
"e": 3128,
"s": 3021,
"text": "You will receive the following result. Here the -e option enables the interpretation of backslash escapes."
},
{
"code": null,
"e": 3146,
"s": 3128,
"text": "Value of a is 10\n"
},
{
"code": null,
"e": 3190,
"s": 3146,
"text": "Following is the result without -e option −"
},
{
"code": null,
"e": 3210,
"s": 3190,
"text": "Value of a is 10\\n\n"
},
{
"code": null,
"e": 3277,
"s": 3210,
"text": "The following escape sequences which can be used in echo command −"
},
{
"code": null,
"e": 3280,
"s": 3277,
"text": "\\\\"
},
{
"code": null,
"e": 3290,
"s": 3280,
"text": "backslash"
},
{
"code": null,
"e": 3293,
"s": 3290,
"text": "\\a"
},
{
"code": null,
"e": 3305,
"s": 3293,
"text": "alert (BEL)"
},
{
"code": null,
"e": 3308,
"s": 3305,
"text": "\\b"
},
{
"code": null,
"e": 3318,
"s": 3308,
"text": "backspace"
},
{
"code": null,
"e": 3322,
"s": 3318,
"text": "\\c "
},
{
"code": null,
"e": 3348,
"s": 3322,
"text": "suppress trailing newline"
},
{
"code": null,
"e": 3352,
"s": 3348,
"text": "\\f "
},
{
"code": null,
"e": 3362,
"s": 3352,
"text": "form feed"
},
{
"code": null,
"e": 3365,
"s": 3362,
"text": "\\n"
},
{
"code": null,
"e": 3374,
"s": 3365,
"text": "new line"
},
{
"code": null,
"e": 3377,
"s": 3374,
"text": "\\r"
},
{
"code": null,
"e": 3393,
"s": 3377,
"text": "carriage return"
},
{
"code": null,
"e": 3397,
"s": 3393,
"text": "\\t "
},
{
"code": null,
"e": 3412,
"s": 3397,
"text": "horizontal tab"
},
{
"code": null,
"e": 3416,
"s": 3412,
"text": "\\v "
},
{
"code": null,
"e": 3429,
"s": 3416,
"text": "vertical tab"
},
{
"code": null,
"e": 3521,
"s": 3429,
"text": "You can use the -E option to disable the interpretation of the backslash escapes (default)."
},
{
"code": null,
"e": 3587,
"s": 3521,
"text": "You can use the -n option to disable the insertion of a new line."
},
{
"code": null,
"e": 3741,
"s": 3587,
"text": "Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands."
},
{
"code": null,
"e": 3808,
"s": 3741,
"text": "The command substitution is performed when a command is given as −"
},
{
"code": null,
"e": 3819,
"s": 3808,
"text": "`command`\n"
},
{
"code": null,
"e": 3930,
"s": 3819,
"text": "When performing the command substitution make sure that you use the backquote, not the single quote character."
},
{
"code": null,
"e": 4089,
"s": 3930,
"text": "Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrates the command substitution −"
},
{
"code": null,
"e": 4228,
"s": 4089,
"text": "#!/bin/sh\n\nDATE=`date`\necho \"Date is $DATE\"\n\nUSERS=`who | wc -l`\necho \"Logged in user are $USERS\"\n\nUP=`date ; uptime`\necho \"Uptime is $UP\""
},
{
"code": null,
"e": 4284,
"s": 4228,
"text": "Upon execution, you will receive the following result −"
},
{
"code": null,
"e": 4447,
"s": 4284,
"text": "Date is Thu Jul 2 03:59:57 MST 2009\nLogged in user are 1\nUptime is Thu Jul 2 03:59:57 MST 2009\n03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15\n"
},
{
"code": null,
"e": 4556,
"s": 4447,
"text": "Variable substitution enables the shell programmer to manipulate the value of a variable based on its state."
},
{
"code": null,
"e": 4621,
"s": 4556,
"text": "Here is the following table for all the possible substitutions −"
},
{
"code": null,
"e": 4628,
"s": 4621,
"text": "${var}"
},
{
"code": null,
"e": 4657,
"s": 4628,
"text": "Substitute the value of var."
},
{
"code": null,
"e": 4670,
"s": 4657,
"text": "${var:-word}"
},
{
"code": null,
"e": 4758,
"s": 4670,
"text": "If var is null or unset, word is substituted for var. The value of var does not change."
},
{
"code": null,
"e": 4771,
"s": 4758,
"text": "${var:=word}"
},
{
"code": null,
"e": 4829,
"s": 4771,
"text": "If var is null or unset, var is set to the value of word."
},
{
"code": null,
"e": 4845,
"s": 4829,
"text": "${var:?message}"
},
{
"code": null,
"e": 4954,
"s": 4845,
"text": "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
},
{
"code": null,
"e": 4967,
"s": 4954,
"text": "${var:+word}"
},
{
"code": null,
"e": 5045,
"s": 4967,
"text": "If var is set, word is substituted for var. The value of var does not change."
},
{
"code": null,
"e": 5121,
"s": 5045,
"text": "Following is the example to show various states of the above substitution −"
},
{
"code": null,
"e": 5503,
"s": 5121,
"text": "#!/bin/sh\n\necho ${var:-\"Variable is not set\"}\necho \"1 - Value of var is ${var}\"\n\necho ${var:=\"Variable is not set\"}\necho \"2 - Value of var is ${var}\"\n\nunset var\necho ${var:+\"This is default value\"}\necho \"3 - Value of var is $var\"\n\nvar=\"Prefix\"\necho ${var:+\"This is default value\"}\necho \"4 - Value of var is $var\"\n\necho ${var:?\"Print this message\"}\necho \"5 - Value of var is ${var}\""
},
{
"code": null,
"e": 5559,
"s": 5503,
"text": "Upon execution, you will receive the following result −"
},
{
"code": null,
"e": 5764,
"s": 5559,
"text": "Variable is not set\n1 - Value of var is\nVariable is not set\n2 - Value of var is Variable is not set\n\n3 - Value of var is\nThis is default value\n4 - Value of var is Prefix\nPrefix\n5 - Value of var is Prefix\n"
},
{
"code": null,
"e": 5799,
"s": 5764,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 5827,
"s": 5799,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5861,
"s": 5827,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5878,
"s": 5861,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5911,
"s": 5878,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5922,
"s": 5911,
"text": " Pradeep D"
},
{
"code": null,
"e": 5957,
"s": 5922,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5973,
"s": 5957,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6006,
"s": 5973,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6018,
"s": 6006,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6050,
"s": 6018,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6058,
"s": 6050,
"text": " Uplatz"
},
{
"code": null,
"e": 6065,
"s": 6058,
"text": " Print"
},
{
"code": null,
"e": 6076,
"s": 6065,
"text": " Add Notes"
}
]
|
Non Access Modifiers in Java
| Java provides a number of non-access modifiers to achieve much other functionality.
The static modifier for creating class methods and variables.
The static modifier for creating class methods and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
The synchronized and volatile modifiers, which are used for threads.
Static Variables
The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared static.
The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of an object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
The static modifier is used to create class methods and variables, as in the following example −
Live Demo
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
private static void addInstance() {
numInstances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " + InstanceCounter.getCount() + " instances");
for (int i = 0; i < 500; ++i) {
new InstanceCounter();
}
System.out.println("Created " + InstanceCounter.getCount() + " instances");
}
}
This will produce the following result −
Started with 0 instances
Created 500 instances
Final Variables
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
public class Test {
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
}
A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.
The main intention of making a method final would be that the content of the method should not be changed by an outsider.
You declare methods using the final modifier in the class declaration, as in the following example −
public class Test {
public final void changeName() {
// body of method
}
}
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
public final class Test {
// body of class
}
Abstract Class
An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise, a compile error will be thrown.
An abstract class may contain both abstract methods as well as normal methods.
abstract class Caravan {
private double price;
private String model;
private String year;
public abstract void goFast(); // an abstract method
public abstract void changeColor();
}
An abstract method is a method declared without any implementation. The methods body (implementation) is provided by the subclass. Abstract methods can never be final or strict.
Any class that extends an abstract class must implement all the abstract methods of the superclass unless the subclass is also an abstract class.
If a class contains one or more abstract methods, then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
public abstract class SuperClass {
abstract void m(); // abstract method
}
class SubClass extends SuperClass {
// implements the abstract method
void m() {
.........
}
}
The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.
public synchronized void showDetails() {
.......
}
An instance variable is marked transient to indicate the JVM to skip the particular variable when serializing the object containing it.
This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
public transient int limit = 55; // will not persist
public int b; // will persist
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copy of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.
public class MyRunnable implements Runnable {
private volatile boolean active;
public void run() {
active = true;
while (active) { // line 1
// some code here
}
}
public void stop() {
active = false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1, the cached value of an action is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile. | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Java provides a number of non-access modifiers to achieve much other functionality."
},
{
"code": null,
"e": 1208,
"s": 1146,
"text": "The static modifier for creating class methods and variables."
},
{
"code": null,
"e": 1270,
"s": 1208,
"text": "The static modifier for creating class methods and variables."
},
{
"code": null,
"e": 1360,
"s": 1270,
"text": "The final modifier for finalizing the implementations of classes, methods, and variables."
},
{
"code": null,
"e": 1450,
"s": 1360,
"text": "The final modifier for finalizing the implementations of classes, methods, and variables."
},
{
"code": null,
"e": 1515,
"s": 1450,
"text": "The abstract modifier for creating abstract classes and methods."
},
{
"code": null,
"e": 1580,
"s": 1515,
"text": "The abstract modifier for creating abstract classes and methods."
},
{
"code": null,
"e": 1649,
"s": 1580,
"text": "The synchronized and volatile modifiers, which are used for threads."
},
{
"code": null,
"e": 1718,
"s": 1649,
"text": "The synchronized and volatile modifiers, which are used for threads."
},
{
"code": null,
"e": 1735,
"s": 1718,
"text": "Static Variables"
},
{
"code": null,
"e": 1948,
"s": 1735,
"text": "The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class."
},
{
"code": null,
"e": 2043,
"s": 1948,
"text": "Static variables are also known as class variables. Local variables cannot be declared static."
},
{
"code": null,
"e": 2158,
"s": 2043,
"text": "The static keyword is used to create methods that will exist independently of any instances created for the class."
},
{
"code": null,
"e": 2380,
"s": 2158,
"text": "Static methods do not use any instance variables of an object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables."
},
{
"code": null,
"e": 2503,
"s": 2380,
"text": "Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method."
},
{
"code": null,
"e": 2600,
"s": 2503,
"text": "The static modifier is used to create class methods and variables, as in the following example −"
},
{
"code": null,
"e": 2610,
"s": 2600,
"text": "Live Demo"
},
{
"code": null,
"e": 3198,
"s": 2610,
"text": "public class InstanceCounter {\n\n private static int numInstances = 0;\n\n protected static int getCount() {\n return numInstances;\n }\n\n private static void addInstance() {\n numInstances++;\n }\n\n InstanceCounter() {\n InstanceCounter.addInstance();\n }\n\n public static void main(String[] arguments) {\n System.out.println(\"Starting with \" + InstanceCounter.getCount() + \" instances\");\n \n for (int i = 0; i < 500; ++i) {\n new InstanceCounter();\n }\n System.out.println(\"Created \" + InstanceCounter.getCount() + \" instances\");\n }\n}"
},
{
"code": null,
"e": 3239,
"s": 3198,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3286,
"s": 3239,
"text": "Started with 0 instances\nCreated 500 instances"
},
{
"code": null,
"e": 3302,
"s": 3286,
"text": "Final Variables"
},
{
"code": null,
"e": 3452,
"s": 3302,
"text": "A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object."
},
{
"code": null,
"e": 3570,
"s": 3452,
"text": "However, the data within the object can be changed. So, the state of the object can be changed but not the reference."
},
{
"code": null,
"e": 3670,
"s": 3570,
"text": "With variables, the final modifier often is used with static to make the constant a class variable."
},
{
"code": null,
"e": 3937,
"s": 3670,
"text": "public class Test {\n final int value = 10;\n\n // The following are examples of declaring constants:\n public static final int BOXWIDTH = 6;\n static final String TITLE = \"Manager\";\n\n public void changeValue() {\n value = 12; // will give an error\n }\n}"
},
{
"code": null,
"e": 4089,
"s": 3937,
"text": "A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass."
},
{
"code": null,
"e": 4211,
"s": 4089,
"text": "The main intention of making a method final would be that the content of the method should not be changed by an outsider."
},
{
"code": null,
"e": 4312,
"s": 4211,
"text": "You declare methods using the final modifier in the class declaration, as in the following example −"
},
{
"code": null,
"e": 4399,
"s": 4312,
"text": "public class Test {\n public final void changeName() {\n // body of method\n }\n}"
},
{
"code": null,
"e": 4594,
"s": 4399,
"text": "The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class."
},
{
"code": null,
"e": 4642,
"s": 4594,
"text": "public final class Test {\n // body of class\n}"
},
{
"code": null,
"e": 4657,
"s": 4642,
"text": "Abstract Class"
},
{
"code": null,
"e": 4792,
"s": 4657,
"text": "An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended."
},
{
"code": null,
"e": 5000,
"s": 4792,
"text": "A class cannot be both abstract and final (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise, a compile error will be thrown."
},
{
"code": null,
"e": 5079,
"s": 5000,
"text": "An abstract class may contain both abstract methods as well as normal methods."
},
{
"code": null,
"e": 5277,
"s": 5079,
"text": "abstract class Caravan {\n private double price;\n private String model;\n private String year;\n public abstract void goFast(); // an abstract method\n public abstract void changeColor();\n}"
},
{
"code": null,
"e": 5455,
"s": 5277,
"text": "An abstract method is a method declared without any implementation. The methods body (implementation) is provided by the subclass. Abstract methods can never be final or strict."
},
{
"code": null,
"e": 5601,
"s": 5455,
"text": "Any class that extends an abstract class must implement all the abstract methods of the superclass unless the subclass is also an abstract class."
},
{
"code": null,
"e": 5754,
"s": 5601,
"text": "If a class contains one or more abstract methods, then the class must be declared abstract. An abstract class does not need to contain abstract methods."
},
{
"code": null,
"e": 5832,
"s": 5754,
"text": "The abstract method ends with a semicolon. Example: public abstract sample();"
},
{
"code": null,
"e": 6023,
"s": 5832,
"text": "public abstract class SuperClass {\n abstract void m(); // abstract method\n}\n\nclass SubClass extends SuperClass {\n // implements the abstract method\n void m() {\n .........\n }\n}"
},
{
"code": null,
"e": 6211,
"s": 6023,
"text": "The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers."
},
{
"code": null,
"e": 6265,
"s": 6211,
"text": "public synchronized void showDetails() {\n .......\n}"
},
{
"code": null,
"e": 6401,
"s": 6265,
"text": "An instance variable is marked transient to indicate the JVM to skip the particular variable when serializing the object containing it."
},
{
"code": null,
"e": 6521,
"s": 6401,
"text": "This modifier is included in the statement that creates the variable, preceding the class or data type of the variable."
},
{
"code": null,
"e": 6608,
"s": 6521,
"text": "public transient int limit = 55; // will not persist\npublic int b; // will persist"
},
{
"code": null,
"e": 6786,
"s": 6608,
"text": "The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory."
},
{
"code": null,
"e": 7016,
"s": 6786,
"text": "Accessing a volatile variable synchronizes all the cached copy of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null."
},
{
"code": null,
"e": 7284,
"s": 7016,
"text": "public class MyRunnable implements Runnable {\n private volatile boolean active;\n\n public void run() {\n active = true;\n while (active) { // line 1\n // some code here\n }\n }\n\n public void stop() {\n active = false; // line 2\n }\n}"
},
{
"code": null,
"e": 7558,
"s": 7284,
"text": "Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1, the cached value of an action is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile."
}
]
|
C# | How to Implement Multiple Interfaces Having Same Method Name - GeeksforGeeks | 04 Apr, 2019
Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface’s members will be given by the class who implements the interface implicitly or explicitly.C# allows the implementation of multiple interfaces with the same method name. To understand how to implement multiple interfaces with the same method name we take an example. In this example, we take two interfaces named as G1 and G2 with the same method name.
Now implement these interfaces in a class named as Geeks and define mymethod() method and when the user will try to call this method, it gives an error because we did not tell the compiler that this method belongs to which interface.
Example:
// C# program to illustrate the concept// of how to inherit multiple interfaces// with the same method nameusing System; // Interface G1 and G2// contains same methodinterface G1 { // interface method void mymethod();} interface G2 { // interface method void mymethod();} // 'Geeks' implements both// G1 and G2 interfaceclass Geeks : G1, G2 { // Defining method // this statement gives an error // because we doesn't specify // the interface name void mymethod() { Console.WriteLine("GeeksforGeeks"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Creating object of Geeks // this statement gives an error // because we doesn't specify // the interface name Geeks obj = new Geeks(); // calling method obj.mymethod(); }}
Compile Time Error:
prog.cs(22,7): error CS0737: `Geeks’ does not implement interface member `G1.mymethod()’ and the best implementing candidate `Geeks.mymethod()’ is not publicprog.cs(11,7): (Location of the symbol related to previous error)prog.cs(28,7): (Location of the symbol related to previous error)prog.cs(22,7): error CS0535: `Geeks’ does not implement interface member `G2.mymethod()’prog.cs(17,7): (Location of the symbol related to previous error)prog.cs(48,7): error CS0122: `Geeks.mymethod()’ is inaccessible due to its protection levelprog.cs(28,7): (Location of the symbol related to previous error)
To remove this error, we will specify the name of the interface with the method name like G1.mymethod(). It tells the compiler that this method belongs to G1 interface. Similarly, G2.mymethod() tells the compiler that this method belongs to the G2 interface.
Example:
// C# program to illustrate the concept // of how to inherit multiple interfaces // with the same method nameusing System; // Interface G1 and G2 // contains same methodinterface G1 { // method declaration void mymethod();} interface G2 { // method declaration void mymethod();} // Geeks implements both // G1 and G2 interfaceclass Geeks : G1, G2{ // Here mymethod belongs to // G1 interface void G1.mymethod(){ Console.WriteLine("GeeksforGeeks");} // Here mymethod belongs to // G2 interface void G2.mymethod(){ Console.WriteLine("GeeksforGeeks");}} // Driver Classpublic class GFG { // Main Method static public void Main () { // Creating object of Geeks // of G1 interface G1 obj = new Geeks(); // calling G1 interface method obj.mymethod(); // Creating object of Geeks // of G2 interface G2 ob = new Geeks(); // calling G2 interface method ob.mymethod(); }}
Output :
GeeksforGeeks
GeeksforGeeks
Note: You can also declare the method as public in the class that implements the interfaces. But the confusion will still remain as in the large program a user can’t differentiate which method of which interface is implemented.
Example:
// C# program to illustrate the concept// of how to inherit multiple interfaces// with the same method name by defining // the method as public in the class // which implements the interfaces.using System; // Interface G1 and G2// contains same methodinterface G1 { // interface method void mymethod();} interface G2 { // interface method void mymethod();} // 'Geeks' implement both// G1 and G2 interfaceclass Geeks : G1, G2 { // Defining method as public public void mymethod() { Console.WriteLine("GeeksforGeeks"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Creating object of Geeks Geeks obj = new Geeks(); // calling method obj.mymethod(); }}
Output:
GeeksforGeeks
CSharp-Interfaces
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
Common Language Runtime (CLR) in C# | [
{
"code": null,
"e": 25457,
"s": 25429,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 25997,
"s": 25457,
"text": "Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface’s members will be given by the class who implements the interface implicitly or explicitly.C# allows the implementation of multiple interfaces with the same method name. To understand how to implement multiple interfaces with the same method name we take an example. In this example, we take two interfaces named as G1 and G2 with the same method name."
},
{
"code": null,
"e": 26231,
"s": 25997,
"text": "Now implement these interfaces in a class named as Geeks and define mymethod() method and when the user will try to call this method, it gives an error because we did not tell the compiler that this method belongs to which interface."
},
{
"code": null,
"e": 26240,
"s": 26231,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept// of how to inherit multiple interfaces// with the same method nameusing System; // Interface G1 and G2// contains same methodinterface G1 { // interface method void mymethod();} interface G2 { // interface method void mymethod();} // 'Geeks' implements both// G1 and G2 interfaceclass Geeks : G1, G2 { // Defining method // this statement gives an error // because we doesn't specify // the interface name void mymethod() { Console.WriteLine(\"GeeksforGeeks\"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Creating object of Geeks // this statement gives an error // because we doesn't specify // the interface name Geeks obj = new Geeks(); // calling method obj.mymethod(); }}",
"e": 27113,
"s": 26240,
"text": null
},
{
"code": null,
"e": 27133,
"s": 27113,
"text": "Compile Time Error:"
},
{
"code": null,
"e": 27730,
"s": 27133,
"text": "prog.cs(22,7): error CS0737: `Geeks’ does not implement interface member `G1.mymethod()’ and the best implementing candidate `Geeks.mymethod()’ is not publicprog.cs(11,7): (Location of the symbol related to previous error)prog.cs(28,7): (Location of the symbol related to previous error)prog.cs(22,7): error CS0535: `Geeks’ does not implement interface member `G2.mymethod()’prog.cs(17,7): (Location of the symbol related to previous error)prog.cs(48,7): error CS0122: `Geeks.mymethod()’ is inaccessible due to its protection levelprog.cs(28,7): (Location of the symbol related to previous error)"
},
{
"code": null,
"e": 27989,
"s": 27730,
"text": "To remove this error, we will specify the name of the interface with the method name like G1.mymethod(). It tells the compiler that this method belongs to G1 interface. Similarly, G2.mymethod() tells the compiler that this method belongs to the G2 interface."
},
{
"code": null,
"e": 27998,
"s": 27989,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept // of how to inherit multiple interfaces // with the same method nameusing System; // Interface G1 and G2 // contains same methodinterface G1 { // method declaration void mymethod();} interface G2 { // method declaration void mymethod();} // Geeks implements both // G1 and G2 interfaceclass Geeks : G1, G2{ // Here mymethod belongs to // G1 interface void G1.mymethod(){ Console.WriteLine(\"GeeksforGeeks\");} // Here mymethod belongs to // G2 interface void G2.mymethod(){ Console.WriteLine(\"GeeksforGeeks\");}} // Driver Classpublic class GFG { // Main Method static public void Main () { // Creating object of Geeks // of G1 interface G1 obj = new Geeks(); // calling G1 interface method obj.mymethod(); // Creating object of Geeks // of G2 interface G2 ob = new Geeks(); // calling G2 interface method ob.mymethod(); }}",
"e": 29045,
"s": 27998,
"text": null
},
{
"code": null,
"e": 29054,
"s": 29045,
"text": "Output :"
},
{
"code": null,
"e": 29083,
"s": 29054,
"text": "GeeksforGeeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 29311,
"s": 29083,
"text": "Note: You can also declare the method as public in the class that implements the interfaces. But the confusion will still remain as in the large program a user can’t differentiate which method of which interface is implemented."
},
{
"code": null,
"e": 29320,
"s": 29311,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept// of how to inherit multiple interfaces// with the same method name by defining // the method as public in the class // which implements the interfaces.using System; // Interface G1 and G2// contains same methodinterface G1 { // interface method void mymethod();} interface G2 { // interface method void mymethod();} // 'Geeks' implement both// G1 and G2 interfaceclass Geeks : G1, G2 { // Defining method as public public void mymethod() { Console.WriteLine(\"GeeksforGeeks\"); }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Creating object of Geeks Geeks obj = new Geeks(); // calling method obj.mymethod(); }}",
"e": 30094,
"s": 29320,
"text": null
},
{
"code": null,
"e": 30102,
"s": 30094,
"text": "Output:"
},
{
"code": null,
"e": 30117,
"s": 30102,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 30135,
"s": 30117,
"text": "CSharp-Interfaces"
},
{
"code": null,
"e": 30138,
"s": 30135,
"text": "C#"
},
{
"code": null,
"e": 30236,
"s": 30138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30264,
"s": 30236,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30279,
"s": 30264,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30302,
"s": 30279,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30324,
"s": 30302,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 30364,
"s": 30324,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 30395,
"s": 30364,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 30411,
"s": 30395,
"text": "C# | Data Types"
},
{
"code": null,
"e": 30423,
"s": 30411,
"text": "C# | Arrays"
},
{
"code": null,
"e": 30451,
"s": 30423,
"text": "HashSet in C# with Examples"
}
]
|
Class getField() method in Java with Examples - GeeksforGeeks | 16 Dec, 2019
The getField() method of java.lang.Class class is used to get the specified field of this class, which is the field that is public and its members. The method returns the specified field of this class in the form of Field objects.
Syntax:
public Field getField(String fieldName)
throws NoSuchFieldException,
SecurityException
Parameter: This method accepts a parameter fieldName which is the Field to get.
Return Value: This method returns the specified field of this class in the form of Field objects.
Exception This method throws:
NoSuchFieldException if a field with the specified name is not found.
NullPointerException if name is null
SecurityException if a security manager is present and the security conditions are not met.
Below programs demonstrate the getField() method.
Example 1:
// Java program to demonstrate getField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String fieldName = "obj"; // Get the field of myClass // using getField() method System.out.println( fieldName + " Field of myClass: " + myClass.getField(fieldName)); }}
Class represented by myClass: class Test
obj Field of myClass: public java.lang.Object Test.obj
Example 2:
// Java program to demonstrate getField() method import java.util.*; class Main { private Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); String fieldName = "obj"; try { // Get the field of myClass // using getField() method System.out.println( fieldName + " Field of myClass: " + myClass.getField(fieldName)); } catch (Exception e) { System.out.println(e); } }}
java.lang.NoSuchFieldException: obj
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getField-java.lang.String-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java | [
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n16 Dec, 2019"
},
{
"code": null,
"e": 24099,
"s": 23868,
"text": "The getField() method of java.lang.Class class is used to get the specified field of this class, which is the field that is public and its members. The method returns the specified field of this class in the form of Field objects."
},
{
"code": null,
"e": 24107,
"s": 24099,
"text": "Syntax:"
},
{
"code": null,
"e": 24216,
"s": 24107,
"text": "public Field getField(String fieldName)\n throws NoSuchFieldException,\n SecurityException\n"
},
{
"code": null,
"e": 24296,
"s": 24216,
"text": "Parameter: This method accepts a parameter fieldName which is the Field to get."
},
{
"code": null,
"e": 24394,
"s": 24296,
"text": "Return Value: This method returns the specified field of this class in the form of Field objects."
},
{
"code": null,
"e": 24424,
"s": 24394,
"text": "Exception This method throws:"
},
{
"code": null,
"e": 24494,
"s": 24424,
"text": "NoSuchFieldException if a field with the specified name is not found."
},
{
"code": null,
"e": 24531,
"s": 24494,
"text": "NullPointerException if name is null"
},
{
"code": null,
"e": 24623,
"s": 24531,
"text": "SecurityException if a security manager is present and the security conditions are not met."
},
{
"code": null,
"e": 24673,
"s": 24623,
"text": "Below programs demonstrate the getField() method."
},
{
"code": null,
"e": 24684,
"s": 24673,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate getField() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String fieldName = \"obj\"; // Get the field of myClass // using getField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getField(fieldName)); }}",
"e": 25342,
"s": 24684,
"text": null
},
{
"code": null,
"e": 25439,
"s": 25342,
"text": "Class represented by myClass: class Test\nobj Field of myClass: public java.lang.Object Test.obj\n"
},
{
"code": null,
"e": 25450,
"s": 25439,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate getField() method import java.util.*; class Main { private Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); String fieldName = \"obj\"; try { // Get the field of myClass // using getField() method System.out.println( fieldName + \" Field of myClass: \" + myClass.getField(fieldName)); } catch (Exception e) { System.out.println(e); } }}",
"e": 26193,
"s": 25450,
"text": null
},
{
"code": null,
"e": 26230,
"s": 26193,
"text": "java.lang.NoSuchFieldException: obj\n"
},
{
"code": null,
"e": 26331,
"s": 26230,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getField-java.lang.String-"
},
{
"code": null,
"e": 26346,
"s": 26331,
"text": "Java-Functions"
},
{
"code": null,
"e": 26364,
"s": 26346,
"text": "Java-lang package"
},
{
"code": null,
"e": 26380,
"s": 26364,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 26385,
"s": 26380,
"text": "Java"
},
{
"code": null,
"e": 26390,
"s": 26385,
"text": "Java"
},
{
"code": null,
"e": 26488,
"s": 26390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26497,
"s": 26488,
"text": "Comments"
},
{
"code": null,
"e": 26510,
"s": 26497,
"text": "Old Comments"
},
{
"code": null,
"e": 26556,
"s": 26510,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26577,
"s": 26556,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26592,
"s": 26577,
"text": "Stream In Java"
},
{
"code": null,
"e": 26611,
"s": 26592,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26653,
"s": 26611,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 26696,
"s": 26653,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26713,
"s": 26696,
"text": "Generics in Java"
},
{
"code": null,
"e": 26743,
"s": 26713,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26769,
"s": 26743,
"text": "Java Programming Examples"
}
]
|
Line detection in python with OpenCV | Houghline method - GeeksforGeeks | 21 Feb, 2022
The Hough Transform is a method that is used in image processing to detect any shape, if that shape can be represented in mathematical form. It can detect the shape even if it is broken or distorted a little bit. We will see how Hough transform works for line detection using the HoughLine transform method. To apply the Houghline method, first an edge detection of the specific image is desirable. For the edge detection technique go through the article Edge detection
Basics of Houghline Method
A line can be represented as y = mx + c or in parametric form, as r = xcosθ + ysinθ where r is the perpendicular distance from origin to the line, and θ is the angle formed by this perpendicular line and horizontal axis measured in counter-clockwise ( That direction varies on how you represent the coordinate system. This representation is used in OpenCV).
So Any line can be represented in these two terms, (r, θ).Working of Houghline method:
First it creates a 2D array or accumulator (to hold values of two parameters) and it is set to zero initially.
Let rows denote the r and columns denote the (θ)theta.
Size of array depends on the accuracy you need. Suppose you want the accuracy of angles to be 1 degree, you need 180 columns(Maximum degree for a straight line is 180).
For r, the maximum distance possible is the diagonal length of the image. So taking one pixel accuracy, number of rows can be diagonal length of the image.
Example: Consider a 100×100 image with a horizontal line at the middle. Take the first point of the line. You know its (x,y) values. Now in the line equation, put the values θ(theta) = 0,1,2,....,180 and check the r you get. For every (r, 0) pair, you increment value by one in the accumulator in its corresponding (r,0) cells. So now in accumulator, the cell (50,90) = 1 along with some other cells. Now take the second point on the line. Do the same as above. Increment the values in the cells corresponding to (r,0) you got. This time, the cell (50,90) = 2. We are actually voting the (r,0) values. You continue this process for every point on the line. At each point, the cell (50,90) will be incremented or voted up, while other cells may or may not be voted up. This way, at the end, the cell (50,90) will have maximum votes. So if you search the accumulator for maximum votes, you get the value (50,90) which says, there is a line in this image at distance 50 from origin and at angle 90 degrees.
Everything explained above is encapsulated in the OpenCV function, cv2.HoughLines(). It simply returns an array of (r, 0) values. r is measured in pixels and 0 is measured in radians.
Python
# Python program to illustrate HoughLine# method for line detectionimport cv2import numpy as np # Reading the required image in# which operations are to be done.# Make sure that the image is in the same# directory in which this python program isimg = cv2.imread('image.jpg') # Convert the img to grayscalegray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Apply edge detection method on the imageedges = cv2.Canny(gray,50,150,apertureSize = 3) # This returns an array of r and theta valueslines = cv2.HoughLines(edges,1,np.pi/180, 200) # The below for loop runs till r and theta values# are in the range of the 2d arrayfor r_theta in lines[0]: r,theta = r_theta[0] # Stores the value of cos(theta) in a a = np.cos(theta) # Stores the value of sin(theta) in b b = np.sin(theta) # x0 stores the value rcos(theta) x0 = a*r # y0 stores the value rsin(theta) y0 = b*r # x1 stores the rounded off value of (rcos(theta)-1000sin(theta)) x1 = int(x0 + 1000*(-b)) # y1 stores the rounded off value of (rsin(theta)+1000cos(theta)) y1 = int(y0 + 1000*(a)) # x2 stores the rounded off value of (rcos(theta)+1000sin(theta)) x2 = int(x0 - 1000*(-b)) # y2 stores the rounded off value of (rsin(theta)-1000cos(theta)) y2 = int(y0 - 1000*(a)) # cv2.line draws a line in img from the point(x1,y1) to (x2,y2). # (0,0,255) denotes the colour of the line to be #drawn. In this case, it is red. cv2.line(img,(x1,y1), (x2,y2), (0,0,255),2) # All the changes made in the input image are finally# written on a new image houghlines.jpgcv2.imwrite('linesDetected.jpg', img)
Elaboration of function(cv2.HoughLines (edges,1,np.pi/180, 200)):
First parameter, Input image should be a binary image, so apply threshold edge detection before finding applying hough transform.Second and third parameters are r and θ(theta) accuracies respectively.Fourth argument is the threshold, which means minimum vote it should get for it to be considered as a line.Remember, number of votes depend upon number of points on the line. So it represents the minimum length of line that should be detected.
First parameter, Input image should be a binary image, so apply threshold edge detection before finding applying hough transform.
Second and third parameters are r and θ(theta) accuracies respectively.
Fourth argument is the threshold, which means minimum vote it should get for it to be considered as a line.
Remember, number of votes depend upon number of points on the line. So it represents the minimum length of line that should be detected.
Alternate simpler method for directly extracting points:
Python3
import cv2import numpy as np # Read imageimage = cv2.imread('path/to/image.png') # Convert image to grayscalegray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # Use canny edge detectionedges = cv2.Canny(gray,50,150,apertureSize=3) # Apply HoughLinesP method to# to directly obtain line end pointslines = cv2.HoughLinesP( edges, # Input edge image 1, # Distance resolution in pixels np.pi/180, # Angle resolution in radians threshold=100, # Min number of votes for valid line minLineLength=5, # Min allowed length of line maxLineGap=10 # Max allowed gap between line for joining them ) # Iterate over pointsfor points in lines: # Extracted points nested in the list x1,y1,x2,y2=points[0] # Draw the lines joing the points # On the original image cv2.line(image,(x1,y1),(x2,y2),(0,255,0),2) # Maintain a simples lookup list for points lines_list.append([(x1,y1),(x2,y2)]) # Save the result imagecv2.imwrite('detectedLines.png',image)
Summarizing the process
In an image analysis context, the coordinates of the point(s) of edge segments (i.e. X,Y ) in the image are known and therefore serve as constants in the parametric line equation, while R(rho) and Theta(θ) are the unknown variables we seek.
If we plot the possible (r) values defined by each (theta), points in cartesian image space map to curves (i.e. sinusoids) in the polar Hough parameter space. This point-to-curve transformation is the Hough transformation for straight lines.
The transform is implemented by quantizing the Hough parameter space into finite intervals or accumulator cells. As the algorithm runs, each (X,Y) is transformed into a discretized (r,0) curve and the accumulator(2D array) cells which lie along this curve are incremented.
Resulting peaks in the accumulator array represent strong evidence that a corresponding straight line exists in the image.
Applications of Hough transform:
It is used to isolate features of a particular shape within an image.Tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise.Used extensively in barcode scanning, verification and recognition
It is used to isolate features of a particular shape within an image.
Tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise.
Used extensively in barcode scanning, verification and recognition
This article is contributed by Pratima Upadhyay. 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.
DevarshiAgarwal
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python | [
{
"code": null,
"e": 24540,
"s": 24512,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25012,
"s": 24540,
"text": "The Hough Transform is a method that is used in image processing to detect any shape, if that shape can be represented in mathematical form. It can detect the shape even if it is broken or distorted a little bit. We will see how Hough transform works for line detection using the HoughLine transform method. To apply the Houghline method, first an edge detection of the specific image is desirable. For the edge detection technique go through the article Edge detection "
},
{
"code": null,
"e": 25039,
"s": 25012,
"text": "Basics of Houghline Method"
},
{
"code": null,
"e": 25399,
"s": 25039,
"text": "A line can be represented as y = mx + c or in parametric form, as r = xcosθ + ysinθ where r is the perpendicular distance from origin to the line, and θ is the angle formed by this perpendicular line and horizontal axis measured in counter-clockwise ( That direction varies on how you represent the coordinate system. This representation is used in OpenCV). "
},
{
"code": null,
"e": 25488,
"s": 25399,
"text": "So Any line can be represented in these two terms, (r, θ).Working of Houghline method: "
},
{
"code": null,
"e": 25599,
"s": 25488,
"text": "First it creates a 2D array or accumulator (to hold values of two parameters) and it is set to zero initially."
},
{
"code": null,
"e": 25654,
"s": 25599,
"text": "Let rows denote the r and columns denote the (θ)theta."
},
{
"code": null,
"e": 25823,
"s": 25654,
"text": "Size of array depends on the accuracy you need. Suppose you want the accuracy of angles to be 1 degree, you need 180 columns(Maximum degree for a straight line is 180)."
},
{
"code": null,
"e": 25979,
"s": 25823,
"text": "For r, the maximum distance possible is the diagonal length of the image. So taking one pixel accuracy, number of rows can be diagonal length of the image."
},
{
"code": null,
"e": 26985,
"s": 25979,
"text": "Example: Consider a 100×100 image with a horizontal line at the middle. Take the first point of the line. You know its (x,y) values. Now in the line equation, put the values θ(theta) = 0,1,2,....,180 and check the r you get. For every (r, 0) pair, you increment value by one in the accumulator in its corresponding (r,0) cells. So now in accumulator, the cell (50,90) = 1 along with some other cells. Now take the second point on the line. Do the same as above. Increment the values in the cells corresponding to (r,0) you got. This time, the cell (50,90) = 2. We are actually voting the (r,0) values. You continue this process for every point on the line. At each point, the cell (50,90) will be incremented or voted up, while other cells may or may not be voted up. This way, at the end, the cell (50,90) will have maximum votes. So if you search the accumulator for maximum votes, you get the value (50,90) which says, there is a line in this image at distance 50 from origin and at angle 90 degrees. "
},
{
"code": null,
"e": 27171,
"s": 26985,
"text": "Everything explained above is encapsulated in the OpenCV function, cv2.HoughLines(). It simply returns an array of (r, 0) values. r is measured in pixels and 0 is measured in radians. "
},
{
"code": null,
"e": 27178,
"s": 27171,
"text": "Python"
},
{
"code": "# Python program to illustrate HoughLine# method for line detectionimport cv2import numpy as np # Reading the required image in# which operations are to be done.# Make sure that the image is in the same# directory in which this python program isimg = cv2.imread('image.jpg') # Convert the img to grayscalegray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Apply edge detection method on the imageedges = cv2.Canny(gray,50,150,apertureSize = 3) # This returns an array of r and theta valueslines = cv2.HoughLines(edges,1,np.pi/180, 200) # The below for loop runs till r and theta values# are in the range of the 2d arrayfor r_theta in lines[0]: r,theta = r_theta[0] # Stores the value of cos(theta) in a a = np.cos(theta) # Stores the value of sin(theta) in b b = np.sin(theta) # x0 stores the value rcos(theta) x0 = a*r # y0 stores the value rsin(theta) y0 = b*r # x1 stores the rounded off value of (rcos(theta)-1000sin(theta)) x1 = int(x0 + 1000*(-b)) # y1 stores the rounded off value of (rsin(theta)+1000cos(theta)) y1 = int(y0 + 1000*(a)) # x2 stores the rounded off value of (rcos(theta)+1000sin(theta)) x2 = int(x0 - 1000*(-b)) # y2 stores the rounded off value of (rsin(theta)-1000cos(theta)) y2 = int(y0 - 1000*(a)) # cv2.line draws a line in img from the point(x1,y1) to (x2,y2). # (0,0,255) denotes the colour of the line to be #drawn. In this case, it is red. cv2.line(img,(x1,y1), (x2,y2), (0,0,255),2) # All the changes made in the input image are finally# written on a new image houghlines.jpgcv2.imwrite('linesDetected.jpg', img)",
"e": 28818,
"s": 27178,
"text": null
},
{
"code": null,
"e": 28886,
"s": 28818,
"text": "Elaboration of function(cv2.HoughLines (edges,1,np.pi/180, 200)): "
},
{
"code": null,
"e": 29332,
"s": 28886,
"text": "First parameter, Input image should be a binary image, so apply threshold edge detection before finding applying hough transform.Second and third parameters are r and θ(theta) accuracies respectively.Fourth argument is the threshold, which means minimum vote it should get for it to be considered as a line.Remember, number of votes depend upon number of points on the line. So it represents the minimum length of line that should be detected. "
},
{
"code": null,
"e": 29462,
"s": 29332,
"text": "First parameter, Input image should be a binary image, so apply threshold edge detection before finding applying hough transform."
},
{
"code": null,
"e": 29534,
"s": 29462,
"text": "Second and third parameters are r and θ(theta) accuracies respectively."
},
{
"code": null,
"e": 29642,
"s": 29534,
"text": "Fourth argument is the threshold, which means minimum vote it should get for it to be considered as a line."
},
{
"code": null,
"e": 29781,
"s": 29642,
"text": "Remember, number of votes depend upon number of points on the line. So it represents the minimum length of line that should be detected. "
},
{
"code": null,
"e": 29842,
"s": 29785,
"text": "Alternate simpler method for directly extracting points:"
},
{
"code": null,
"e": 29850,
"s": 29842,
"text": "Python3"
},
{
"code": "import cv2import numpy as np # Read imageimage = cv2.imread('path/to/image.png') # Convert image to grayscalegray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # Use canny edge detectionedges = cv2.Canny(gray,50,150,apertureSize=3) # Apply HoughLinesP method to# to directly obtain line end pointslines = cv2.HoughLinesP( edges, # Input edge image 1, # Distance resolution in pixels np.pi/180, # Angle resolution in radians threshold=100, # Min number of votes for valid line minLineLength=5, # Min allowed length of line maxLineGap=10 # Max allowed gap between line for joining them ) # Iterate over pointsfor points in lines: # Extracted points nested in the list x1,y1,x2,y2=points[0] # Draw the lines joing the points # On the original image cv2.line(image,(x1,y1),(x2,y2),(0,255,0),2) # Maintain a simples lookup list for points lines_list.append([(x1,y1),(x2,y2)]) # Save the result imagecv2.imwrite('detectedLines.png',image)",
"e": 30882,
"s": 29850,
"text": null
},
{
"code": null,
"e": 30908,
"s": 30884,
"text": "Summarizing the process"
},
{
"code": null,
"e": 31151,
"s": 30910,
"text": "In an image analysis context, the coordinates of the point(s) of edge segments (i.e. X,Y ) in the image are known and therefore serve as constants in the parametric line equation, while R(rho) and Theta(θ) are the unknown variables we seek."
},
{
"code": null,
"e": 31393,
"s": 31151,
"text": "If we plot the possible (r) values defined by each (theta), points in cartesian image space map to curves (i.e. sinusoids) in the polar Hough parameter space. This point-to-curve transformation is the Hough transformation for straight lines."
},
{
"code": null,
"e": 31666,
"s": 31393,
"text": "The transform is implemented by quantizing the Hough parameter space into finite intervals or accumulator cells. As the algorithm runs, each (X,Y) is transformed into a discretized (r,0) curve and the accumulator(2D array) cells which lie along this curve are incremented."
},
{
"code": null,
"e": 31789,
"s": 31666,
"text": "Resulting peaks in the accumulator array represent strong evidence that a corresponding straight line exists in the image."
},
{
"code": null,
"e": 31824,
"s": 31789,
"text": "Applications of Hough transform: "
},
{
"code": null,
"e": 32054,
"s": 31824,
"text": "It is used to isolate features of a particular shape within an image.Tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise.Used extensively in barcode scanning, verification and recognition"
},
{
"code": null,
"e": 32124,
"s": 32054,
"text": "It is used to isolate features of a particular shape within an image."
},
{
"code": null,
"e": 32219,
"s": 32124,
"text": "Tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise."
},
{
"code": null,
"e": 32286,
"s": 32219,
"text": "Used extensively in barcode scanning, verification and recognition"
},
{
"code": null,
"e": 32711,
"s": 32286,
"text": "This article is contributed by Pratima Upadhyay. 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": 32727,
"s": 32711,
"text": "DevarshiAgarwal"
},
{
"code": null,
"e": 32744,
"s": 32727,
"text": "Image-Processing"
},
{
"code": null,
"e": 32751,
"s": 32744,
"text": "OpenCV"
},
{
"code": null,
"e": 32758,
"s": 32751,
"text": "Python"
},
{
"code": null,
"e": 32856,
"s": 32758,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32865,
"s": 32856,
"text": "Comments"
},
{
"code": null,
"e": 32878,
"s": 32865,
"text": "Old Comments"
},
{
"code": null,
"e": 32896,
"s": 32878,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32918,
"s": 32896,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32950,
"s": 32918,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32992,
"s": 32950,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 33018,
"s": 32992,
"text": "Python String | replace()"
},
{
"code": null,
"e": 33055,
"s": 33018,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 33084,
"s": 33055,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 33139,
"s": 33084,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 33195,
"s": 33139,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
]
|
Creating Servlet Example in Eclipse - GeeksforGeeks | 30 Dec, 2021
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.
Prerequisites:
Eclipse IDE installed – You can download from https://www.eclipse.org/downloads/
Running server – To run the servlet, we need a server. we can use any Webserver/Application server such as IBM Websphere, Glassfish, Tomcat, etc., in this example we will be using Apache Tomcat server. You can download the latest Tomcat version from https://tomcat.apache.org/
Once the Eclipse is installed and configured with the Tomcat server, below are the steps to create a basic Servlet in Eclipse IDE.
In this example, we will create a basic servlet that displays a Welcome message to the user in the browser.
Step 1: Create a Dynamic web project
In Eclipse, go to File -> New -> Dynamic Web Project and click on it.
After clicking on Dynamic web project, the below window will open to enter the required project details.
Enter the Project Name.
Check if the location where the project saves is correct.
Check if the Run time selected for the project is displaying. If you want to change any of the configurations for runtime, you can do by clicking Modify.
Click on Next.
The source folders on the build path and the classes folder will be displayed here.
Click on Next.
This is the web module creation, where all your HTML and JSP pages will be added.
We can also generate a Deployment Descriptor – web.xml file to define the mappings between URL paths and the servlets to handle the requests with those paths. This can also be done using @WebServlet() annotation in the Servlet class.
In this example, we will be using annotation in our servlet class to map the URL path.
But for the demonstration purpose to show the web.xml file creation in the project, we will select the web.xml checkbox also.
Click on Finish.
Project Structure
In this way, the project structure should be created.
Step 2: servlet-api.jar file
As we are working with servlets, we need to have the servlet-api.jar file in our project. This jar is a library that contains all the interfaces and classes of the Servlet API, so we can use its functionality to develop our web application.
In this example, we are using the Apache Tomcat server to run the project.
Tomcat container is an open-source Java servlet container that implements several core Java enterprise functionalities like the Java Servlet, JSP, etc., so it provides this servlet-api.jar file by default.
You can check the jar file in the below path if you are using the Tomcat server only.
As you can see, under Apache Tomcat, there is a servlet-api.jar file by default.
For Different servers:
In case, if you are using a different server and the servlet-api.jar file is not there, you can download it from Maven Repository.
Add the downloaded jar file as an external jar to your project like below,
Go to the project name and right-click on it. Go to Build Path -> Configure Build Path.
In this window, it will show all the libraries that are associated with the project, and also you can add any required jar files to your project.
Go to the Libraries tab and click on Add External JARs.
Select the servlet-api.jar file from the location you downloaded and add.
Once the jar file is added, click on Apply and Close.
The added jar file will be visible under the lib folder in your project.
Step 3: Create Servlet Class
To create a Servlet, go to folder src -> New -> Servlet.
If the Servlet option is not there, go to Other and search for Servlet.
It is a good practice to create Java classes inside Packages.
Enter the package name and Class name.
Java Servlets are available under javax.servlet.http.HttpServlet. So the Superclass is HttpServlet.
Click on Next.
As we learned about the URL mappings while creating the project, we can specify those URL mapping for the particular servlet here.
The URL specified here should be used in mapping the servlets either in web.xml or by using annotation.
It will show the default mapping name but if you want, you can change that by selecting the URL and clicking on Edit.
Click on Next.
HTTP Servlet is a protocol-specific Servlet and it provides all these methods that are shown in the above screenshot.
We can use these methods based on our requirements.
For example, if we want to implement logic while initialization of the servlet, we can override the init() method.
For HTTP GET requests, to get the information for the request, we can use the doGet() method.
Get more information on HTTP Servlet methods here.
In this example, we are just showing a Welcome message to the user. So, select the doGet Checkbox.
Click on Finish.
HelloServlet.java
As shown above, it creates the HelloServlet.java Servlet class with the doGet() method we selected.
As you can see, it automatically provided the @WebServlet(“/HelloServlet”) annotation for this servlet to map the URL. So, there is no need to enter the mapping again in the web.xml file.
In Java for every class there will be a default constructor, so that constructor is also auto-generated here.
If you are aware of the Serialization concept in Java, the serialVersionUID which is a version number associated with every serialization class is also generated while creating a Servlet in Eclipse IDE.
Step 4: Implement the Logic
In the doGet() method, implement the logic to display the welcome message to the user.
HelloServlet.java
Java
package com.welcome; import java.io.IOException;import java.io.PrintWriter; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet("/HelloServlet")public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<html><body>"); out.print("<h2>Welcome to GeeksForGeeks</h2>"); out.print("</body></html>"); }}
Once we get the Get request from the browser, the doGet() method will be executed.
Here, we are setting the response content type as “text/html” so that the response that is being sent to the client/browser will be considered as text/html.
In the java.io package, Java provides a PrintWriter class to print the formatted output to the text-output streams.
So, get the PrintWriter object and print the Welcome Message.
You need to add all the required packages in the servlet class.
As we specified the content type as “text/html”, the tags we mentioned in the output stream – out.print() will be considered as the HTML tags and the message “Welcome to GeeksForGeeks” will be written in the response to the browser.
Step 5: Run the Project
Right-click on the HelloServlet.java class, Run As -> Run on Server.
If you want to Debug the servlet, you can click on Debug also here.
Make sure the Tomcat server is configured properly on localhost and click on Next.
Check the Project you created is in configured section and then click on Finish.
If the project is showing in the Available section, select the project and click on Add to configure the project on the server.
Output:
Once the server is started, it will configure and run the HelloServlet.java file on the server.
You can run the URL: http://localhost:8080/JavaServlets/HelloServlet in the browser.
Make sure the URL specified in the Servlet “/HelloServlet” is mapped correctly.
java-servlet
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
Strings in Java
HashMap get() Method in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23973,
"s": 23945,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 24220,
"s": 23973,
"text": "Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. "
},
{
"code": null,
"e": 24235,
"s": 24220,
"text": "Prerequisites:"
},
{
"code": null,
"e": 24316,
"s": 24235,
"text": "Eclipse IDE installed – You can download from https://www.eclipse.org/downloads/"
},
{
"code": null,
"e": 24593,
"s": 24316,
"text": "Running server – To run the servlet, we need a server. we can use any Webserver/Application server such as IBM Websphere, Glassfish, Tomcat, etc., in this example we will be using Apache Tomcat server. You can download the latest Tomcat version from https://tomcat.apache.org/"
},
{
"code": null,
"e": 24724,
"s": 24593,
"text": "Once the Eclipse is installed and configured with the Tomcat server, below are the steps to create a basic Servlet in Eclipse IDE."
},
{
"code": null,
"e": 24832,
"s": 24724,
"text": "In this example, we will create a basic servlet that displays a Welcome message to the user in the browser."
},
{
"code": null,
"e": 24869,
"s": 24832,
"text": "Step 1: Create a Dynamic web project"
},
{
"code": null,
"e": 24939,
"s": 24869,
"text": "In Eclipse, go to File -> New -> Dynamic Web Project and click on it."
},
{
"code": null,
"e": 25044,
"s": 24939,
"text": "After clicking on Dynamic web project, the below window will open to enter the required project details."
},
{
"code": null,
"e": 25068,
"s": 25044,
"text": "Enter the Project Name."
},
{
"code": null,
"e": 25126,
"s": 25068,
"text": "Check if the location where the project saves is correct."
},
{
"code": null,
"e": 25280,
"s": 25126,
"text": "Check if the Run time selected for the project is displaying. If you want to change any of the configurations for runtime, you can do by clicking Modify."
},
{
"code": null,
"e": 25295,
"s": 25280,
"text": "Click on Next."
},
{
"code": null,
"e": 25379,
"s": 25295,
"text": "The source folders on the build path and the classes folder will be displayed here."
},
{
"code": null,
"e": 25394,
"s": 25379,
"text": "Click on Next."
},
{
"code": null,
"e": 25476,
"s": 25394,
"text": "This is the web module creation, where all your HTML and JSP pages will be added."
},
{
"code": null,
"e": 25710,
"s": 25476,
"text": "We can also generate a Deployment Descriptor – web.xml file to define the mappings between URL paths and the servlets to handle the requests with those paths. This can also be done using @WebServlet() annotation in the Servlet class."
},
{
"code": null,
"e": 25797,
"s": 25710,
"text": "In this example, we will be using annotation in our servlet class to map the URL path."
},
{
"code": null,
"e": 25923,
"s": 25797,
"text": "But for the demonstration purpose to show the web.xml file creation in the project, we will select the web.xml checkbox also."
},
{
"code": null,
"e": 25940,
"s": 25923,
"text": "Click on Finish."
},
{
"code": null,
"e": 25958,
"s": 25940,
"text": "Project Structure"
},
{
"code": null,
"e": 26012,
"s": 25958,
"text": "In this way, the project structure should be created."
},
{
"code": null,
"e": 26042,
"s": 26012,
"text": "Step 2: servlet-api.jar file "
},
{
"code": null,
"e": 26283,
"s": 26042,
"text": "As we are working with servlets, we need to have the servlet-api.jar file in our project. This jar is a library that contains all the interfaces and classes of the Servlet API, so we can use its functionality to develop our web application."
},
{
"code": null,
"e": 26358,
"s": 26283,
"text": "In this example, we are using the Apache Tomcat server to run the project."
},
{
"code": null,
"e": 26564,
"s": 26358,
"text": "Tomcat container is an open-source Java servlet container that implements several core Java enterprise functionalities like the Java Servlet, JSP, etc., so it provides this servlet-api.jar file by default."
},
{
"code": null,
"e": 26650,
"s": 26564,
"text": "You can check the jar file in the below path if you are using the Tomcat server only."
},
{
"code": null,
"e": 26731,
"s": 26650,
"text": "As you can see, under Apache Tomcat, there is a servlet-api.jar file by default."
},
{
"code": null,
"e": 26754,
"s": 26731,
"text": "For Different servers:"
},
{
"code": null,
"e": 26885,
"s": 26754,
"text": "In case, if you are using a different server and the servlet-api.jar file is not there, you can download it from Maven Repository."
},
{
"code": null,
"e": 26960,
"s": 26885,
"text": "Add the downloaded jar file as an external jar to your project like below,"
},
{
"code": null,
"e": 27048,
"s": 26960,
"text": "Go to the project name and right-click on it. Go to Build Path -> Configure Build Path."
},
{
"code": null,
"e": 27194,
"s": 27048,
"text": "In this window, it will show all the libraries that are associated with the project, and also you can add any required jar files to your project."
},
{
"code": null,
"e": 27250,
"s": 27194,
"text": "Go to the Libraries tab and click on Add External JARs."
},
{
"code": null,
"e": 27324,
"s": 27250,
"text": "Select the servlet-api.jar file from the location you downloaded and add."
},
{
"code": null,
"e": 27378,
"s": 27324,
"text": "Once the jar file is added, click on Apply and Close."
},
{
"code": null,
"e": 27451,
"s": 27378,
"text": "The added jar file will be visible under the lib folder in your project."
},
{
"code": null,
"e": 27480,
"s": 27451,
"text": "Step 3: Create Servlet Class"
},
{
"code": null,
"e": 27537,
"s": 27480,
"text": "To create a Servlet, go to folder src -> New -> Servlet."
},
{
"code": null,
"e": 27609,
"s": 27537,
"text": "If the Servlet option is not there, go to Other and search for Servlet."
},
{
"code": null,
"e": 27671,
"s": 27609,
"text": "It is a good practice to create Java classes inside Packages."
},
{
"code": null,
"e": 27710,
"s": 27671,
"text": "Enter the package name and Class name."
},
{
"code": null,
"e": 27810,
"s": 27710,
"text": "Java Servlets are available under javax.servlet.http.HttpServlet. So the Superclass is HttpServlet."
},
{
"code": null,
"e": 27825,
"s": 27810,
"text": "Click on Next."
},
{
"code": null,
"e": 27956,
"s": 27825,
"text": "As we learned about the URL mappings while creating the project, we can specify those URL mapping for the particular servlet here."
},
{
"code": null,
"e": 28060,
"s": 27956,
"text": "The URL specified here should be used in mapping the servlets either in web.xml or by using annotation."
},
{
"code": null,
"e": 28178,
"s": 28060,
"text": "It will show the default mapping name but if you want, you can change that by selecting the URL and clicking on Edit."
},
{
"code": null,
"e": 28193,
"s": 28178,
"text": "Click on Next."
},
{
"code": null,
"e": 28311,
"s": 28193,
"text": "HTTP Servlet is a protocol-specific Servlet and it provides all these methods that are shown in the above screenshot."
},
{
"code": null,
"e": 28363,
"s": 28311,
"text": "We can use these methods based on our requirements."
},
{
"code": null,
"e": 28478,
"s": 28363,
"text": "For example, if we want to implement logic while initialization of the servlet, we can override the init() method."
},
{
"code": null,
"e": 28572,
"s": 28478,
"text": "For HTTP GET requests, to get the information for the request, we can use the doGet() method."
},
{
"code": null,
"e": 28623,
"s": 28572,
"text": "Get more information on HTTP Servlet methods here."
},
{
"code": null,
"e": 28722,
"s": 28623,
"text": "In this example, we are just showing a Welcome message to the user. So, select the doGet Checkbox."
},
{
"code": null,
"e": 28739,
"s": 28722,
"text": "Click on Finish."
},
{
"code": null,
"e": 28757,
"s": 28739,
"text": "HelloServlet.java"
},
{
"code": null,
"e": 28857,
"s": 28757,
"text": "As shown above, it creates the HelloServlet.java Servlet class with the doGet() method we selected."
},
{
"code": null,
"e": 29045,
"s": 28857,
"text": "As you can see, it automatically provided the @WebServlet(“/HelloServlet”) annotation for this servlet to map the URL. So, there is no need to enter the mapping again in the web.xml file."
},
{
"code": null,
"e": 29155,
"s": 29045,
"text": "In Java for every class there will be a default constructor, so that constructor is also auto-generated here."
},
{
"code": null,
"e": 29358,
"s": 29155,
"text": "If you are aware of the Serialization concept in Java, the serialVersionUID which is a version number associated with every serialization class is also generated while creating a Servlet in Eclipse IDE."
},
{
"code": null,
"e": 29386,
"s": 29358,
"text": "Step 4: Implement the Logic"
},
{
"code": null,
"e": 29473,
"s": 29386,
"text": "In the doGet() method, implement the logic to display the welcome message to the user."
},
{
"code": null,
"e": 29491,
"s": 29473,
"text": "HelloServlet.java"
},
{
"code": null,
"e": 29496,
"s": 29491,
"text": "Java"
},
{
"code": "package com.welcome; import java.io.IOException;import java.io.PrintWriter; import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; @WebServlet(\"/HelloServlet\")public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(\"text/html\"); PrintWriter out = response.getWriter(); out.print(\"<html><body>\"); out.print(\"<h2>Welcome to GeeksForGeeks</h2>\"); out.print(\"</body></html>\"); }}",
"e": 30392,
"s": 29496,
"text": null
},
{
"code": null,
"e": 30475,
"s": 30392,
"text": "Once we get the Get request from the browser, the doGet() method will be executed."
},
{
"code": null,
"e": 30632,
"s": 30475,
"text": "Here, we are setting the response content type as “text/html” so that the response that is being sent to the client/browser will be considered as text/html."
},
{
"code": null,
"e": 30748,
"s": 30632,
"text": "In the java.io package, Java provides a PrintWriter class to print the formatted output to the text-output streams."
},
{
"code": null,
"e": 30810,
"s": 30748,
"text": "So, get the PrintWriter object and print the Welcome Message."
},
{
"code": null,
"e": 30874,
"s": 30810,
"text": "You need to add all the required packages in the servlet class."
},
{
"code": null,
"e": 31107,
"s": 30874,
"text": "As we specified the content type as “text/html”, the tags we mentioned in the output stream – out.print() will be considered as the HTML tags and the message “Welcome to GeeksForGeeks” will be written in the response to the browser."
},
{
"code": null,
"e": 31131,
"s": 31107,
"text": "Step 5: Run the Project"
},
{
"code": null,
"e": 31200,
"s": 31131,
"text": "Right-click on the HelloServlet.java class, Run As -> Run on Server."
},
{
"code": null,
"e": 31268,
"s": 31200,
"text": "If you want to Debug the servlet, you can click on Debug also here."
},
{
"code": null,
"e": 31351,
"s": 31268,
"text": "Make sure the Tomcat server is configured properly on localhost and click on Next."
},
{
"code": null,
"e": 31432,
"s": 31351,
"text": "Check the Project you created is in configured section and then click on Finish."
},
{
"code": null,
"e": 31560,
"s": 31432,
"text": "If the project is showing in the Available section, select the project and click on Add to configure the project on the server."
},
{
"code": null,
"e": 31568,
"s": 31560,
"text": "Output:"
},
{
"code": null,
"e": 31664,
"s": 31568,
"text": "Once the server is started, it will configure and run the HelloServlet.java file on the server."
},
{
"code": null,
"e": 31749,
"s": 31664,
"text": "You can run the URL: http://localhost:8080/JavaServlets/HelloServlet in the browser."
},
{
"code": null,
"e": 31829,
"s": 31749,
"text": "Make sure the URL specified in the Servlet “/HelloServlet” is mapped correctly."
},
{
"code": null,
"e": 31842,
"s": 31829,
"text": "java-servlet"
},
{
"code": null,
"e": 31849,
"s": 31842,
"text": "Picked"
},
{
"code": null,
"e": 31854,
"s": 31849,
"text": "Java"
},
{
"code": null,
"e": 31859,
"s": 31854,
"text": "Java"
},
{
"code": null,
"e": 31957,
"s": 31859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31966,
"s": 31957,
"text": "Comments"
},
{
"code": null,
"e": 31979,
"s": 31966,
"text": "Old Comments"
},
{
"code": null,
"e": 32025,
"s": 31979,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32046,
"s": 32025,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32061,
"s": 32046,
"text": "Stream In Java"
},
{
"code": null,
"e": 32080,
"s": 32061,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32097,
"s": 32080,
"text": "Generics in Java"
},
{
"code": null,
"e": 32127,
"s": 32097,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32170,
"s": 32127,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 32186,
"s": 32170,
"text": "Strings in Java"
},
{
"code": null,
"e": 32215,
"s": 32186,
"text": "HashMap get() Method in Java"
}
]
|
Get and Find commands in Cypress | Cypress has the get() and find() methods to find elements based on locators on the
page. The objective achieved by these two methods are almost identical. The get()
method fetches one or a list of web elements with the help of the css locators
specified as a parameter to that method.
cy.get(selector, args)
The second parameter of the get() method is optional. There can be of three types
of parameter as listed below −
log − The default value of log parameter is true. This determines if there will
be logging of the command on the console.
log − The default value of log parameter is true. This determines if there will
be logging of the command on the console.
cy.get('.product', { log: false });
withinSubject − The default value of withinSubject parameter is null. This
determines from where the element should be searched on the page. If omitted, it starts from the element root.
withinSubject − The default value of withinSubject parameter is null. This
determines from where the element should be searched on the page. If omitted, it starts from the element root.
cy.get('.p',{ withinSubject : document.getElementById('#id')};
timeout − The default value of timeout parameter is
defaultCommandTimeout (4000 milliseconds) . This determines the waiting
time to fetch the element before throwing an error.
timeout − The default value of timeout parameter is
defaultCommandTimeout (4000 milliseconds) . This determines the waiting
time to fetch the element before throwing an error.
cy.get('.p',{ timeout: 5000 });
We can get a list of elements from the get() method. Out of the list or array of
elements, we have to choose one of them with the help of eq() method. The eq()
method fetches the a DOM element at a particular index starting from index 0.
cy.get('.p') .eq(2).should('contain', 'Tutorialspoint');
The find() method fetches one or multiple elements matching with the selector
passed as an argument. The difference between get() and find() methods is that
the find() method needs to be chained with other methods like get(). It cannot be
used independently with the cy object.
.find(selector, args)
The second parameter of the find() method is optional. There can be of two types
of parameter as listed below −
log − The default value of log parameter is true. This determines if there will
be logging of the command on the console.
log − The default value of log parameter is true. This determines if there will
be logging of the command on the console.
cy.get('#parent').find('img', { log: false });
timeout − The default value of timeout parameter is
defaultCommandTimeout (4000 milliseconds). This determines the waiting
time to fetch the element before throwing an error.
timeout − The default value of timeout parameter is
defaultCommandTimeout (4000 milliseconds). This determines the waiting
time to fetch the element before throwing an error.
cy.get('#parent').find('img', timeout: 5000 });
A find() command helps to locate elements which are nested within another
element or mostly if they have parent child relationship. The find() method helps
to locate elements in a faster and efficient way.
Code Implementation with get and find methods.
// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/index.htm");
// enter test in the edit box
// assertion to validate the number of child elements
cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);
// locate element with get and find method
cy.get('#gs_50d > tbody > tr > td'). find('input')
//enter test in the edit box
.type('Cypress');
});
}); | [
{
"code": null,
"e": 1347,
"s": 1062,
"text": "Cypress has the get() and find() methods to find elements based on locators on the\npage. The objective achieved by these two methods are almost identical. The get()\nmethod fetches one or a list of web elements with the help of the css locators\nspecified as a parameter to that method."
},
{
"code": null,
"e": 1370,
"s": 1347,
"text": "cy.get(selector, args)"
},
{
"code": null,
"e": 1483,
"s": 1370,
"text": "The second parameter of the get() method is optional. There can be of three types\nof parameter as listed below −"
},
{
"code": null,
"e": 1605,
"s": 1483,
"text": "log − The default value of log parameter is true. This determines if there will\nbe logging of the command on the console."
},
{
"code": null,
"e": 1727,
"s": 1605,
"text": "log − The default value of log parameter is true. This determines if there will\nbe logging of the command on the console."
},
{
"code": null,
"e": 1763,
"s": 1727,
"text": "cy.get('.product', { log: false });"
},
{
"code": null,
"e": 1949,
"s": 1763,
"text": "withinSubject − The default value of withinSubject parameter is null. This\ndetermines from where the element should be searched on the page. If omitted, it starts from the element root."
},
{
"code": null,
"e": 2135,
"s": 1949,
"text": "withinSubject − The default value of withinSubject parameter is null. This\ndetermines from where the element should be searched on the page. If omitted, it starts from the element root."
},
{
"code": null,
"e": 2198,
"s": 2135,
"text": "cy.get('.p',{ withinSubject : document.getElementById('#id')};"
},
{
"code": null,
"e": 2374,
"s": 2198,
"text": "timeout − The default value of timeout parameter is\ndefaultCommandTimeout (4000 milliseconds) . This determines the waiting\ntime to fetch the element before throwing an error."
},
{
"code": null,
"e": 2550,
"s": 2374,
"text": "timeout − The default value of timeout parameter is\ndefaultCommandTimeout (4000 milliseconds) . This determines the waiting\ntime to fetch the element before throwing an error."
},
{
"code": null,
"e": 2582,
"s": 2550,
"text": "cy.get('.p',{ timeout: 5000 });"
},
{
"code": null,
"e": 2820,
"s": 2582,
"text": "We can get a list of elements from the get() method. Out of the list or array of\nelements, we have to choose one of them with the help of eq() method. The eq()\nmethod fetches the a DOM element at a particular index starting from index 0."
},
{
"code": null,
"e": 2877,
"s": 2820,
"text": "cy.get('.p') .eq(2).should('contain', 'Tutorialspoint');"
},
{
"code": null,
"e": 3155,
"s": 2877,
"text": "The find() method fetches one or multiple elements matching with the selector\npassed as an argument. The difference between get() and find() methods is that\nthe find() method needs to be chained with other methods like get(). It cannot be\nused independently with the cy object."
},
{
"code": null,
"e": 3177,
"s": 3155,
"text": ".find(selector, args)"
},
{
"code": null,
"e": 3289,
"s": 3177,
"text": "The second parameter of the find() method is optional. There can be of two types\nof parameter as listed below −"
},
{
"code": null,
"e": 3411,
"s": 3289,
"text": "log − The default value of log parameter is true. This determines if there will\nbe logging of the command on the console."
},
{
"code": null,
"e": 3533,
"s": 3411,
"text": "log − The default value of log parameter is true. This determines if there will\nbe logging of the command on the console."
},
{
"code": null,
"e": 3580,
"s": 3533,
"text": "cy.get('#parent').find('img', { log: false });"
},
{
"code": null,
"e": 3755,
"s": 3580,
"text": "timeout − The default value of timeout parameter is\ndefaultCommandTimeout (4000 milliseconds). This determines the waiting\ntime to fetch the element before throwing an error."
},
{
"code": null,
"e": 3930,
"s": 3755,
"text": "timeout − The default value of timeout parameter is\ndefaultCommandTimeout (4000 milliseconds). This determines the waiting\ntime to fetch the element before throwing an error."
},
{
"code": null,
"e": 3978,
"s": 3930,
"text": "cy.get('#parent').find('img', timeout: 5000 });"
},
{
"code": null,
"e": 4184,
"s": 3978,
"text": "A find() command helps to locate elements which are nested within another\nelement or mostly if they have parent child relationship. The find() method helps\nto locate elements in a faster and efficient way."
},
{
"code": null,
"e": 4231,
"s": 4184,
"text": "Code Implementation with get and find methods."
},
{
"code": null,
"e": 4775,
"s": 4231,
"text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n // test step to launch a URL\n cy.visit(\"https://www.tutorialspoint.com/index.htm\");\n // enter test in the edit box\n // assertion to validate the number of child elements\n cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);\n // locate element with get and find method\n cy.get('#gs_50d > tbody > tr > td'). find('input')\n //enter test in the edit box\n .type('Cypress');\n });\n});"
}
]
|
Python String rsplit() Method | 19 Aug, 2021
Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator.
Syntax:
str.rsplit(separator, maxsplit)
Parameters:
separator: The is a delimiter. The string splits at this specified separator starting from the right side. It is not provided then any white space is a separator.
maxsplit: It is a number, which tells us to split the string into a maximum of provided number of times. If it is not provided then there is no limit.
Return:
Returns a list of strings after breaking the given string from the right side by the specified separator.
Error:
We will not get any error even if we are not passing any argument.
Python3
# Python code to split a string# using rsplit. # Splits at spaceword = 'geeks for geeks'print(word.rsplit()) # Splits at 'g'. Note that we have# provided maximum limit as 1. So# from right, one splitting happens# and we get "eeks" and "geeks, for, "word = 'geeks, for, geeks'print(word.rsplit('g', 1)) # Splitting at '@' with maximum splitting# as 1word = 'geeks@for@geeks'print(word.rsplit('@', 1))
Output:
['geeks', 'for', 'geeks']
['geeks, for, ', 'eeks']
['geeks@for', 'geeks']
Python3
word = 'geeks, for, geeks, pawan' # maxsplit: 0print(word.rsplit(', ', 0)) # maxsplit: 4print(word.rsplit(', ', 4)) word = 'geeks@for@geeks@for@geeks' # maxsplit: 1print(word.rsplit('@', 1)) # maxsplit: 2print(word.rsplit('@', 2))
Output:
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks@for@geeks@for', 'geeks']
['geeks@for@geeks', 'for', 'geeks']
Python3
word = 'geeks for geeks' # Since separator is 'None', # so, will be splitted at spaceprint(word.rsplit(None, 1)) print(word.rsplit(None, 2)) # Also observe theseprint('@@@@@geeks@for@geeks'.rsplit('@'))print('@@@@@geeks@for@geeks'.rsplit('@', 1))print('@@@@@geeks@for@geeks'.rsplit('@', 3))print('@@@@@geeks@for@geeks'.rsplit('@', 5))
Output:
['geeks for', 'geeks']
['geeks', 'for', 'geeks']
['', '', '', '', '', 'geeks', 'for', 'geeks']
['@@@@@geeks@for', 'geeks']
['@@@@', 'geeks', 'for', 'geeks']
['@@', '', '', 'geeks', 'for', 'geeks']
anikakapoor
AmiyaRanjanRout
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator."
},
{
"code": null,
"e": 173,
"s": 164,
"text": "Syntax: "
},
{
"code": null,
"e": 205,
"s": 173,
"text": "str.rsplit(separator, maxsplit)"
},
{
"code": null,
"e": 219,
"s": 205,
"text": "Parameters: "
},
{
"code": null,
"e": 382,
"s": 219,
"text": "separator: The is a delimiter. The string splits at this specified separator starting from the right side. It is not provided then any white space is a separator."
},
{
"code": null,
"e": 535,
"s": 382,
"text": "maxsplit: It is a number, which tells us to split the string into a maximum of provided number of times. If it is not provided then there is no limit. "
},
{
"code": null,
"e": 543,
"s": 535,
"text": "Return:"
},
{
"code": null,
"e": 649,
"s": 543,
"text": "Returns a list of strings after breaking the given string from the right side by the specified separator."
},
{
"code": null,
"e": 658,
"s": 649,
"text": "Error: "
},
{
"code": null,
"e": 725,
"s": 658,
"text": "We will not get any error even if we are not passing any argument."
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Python3"
},
{
"code": "# Python code to split a string# using rsplit. # Splits at spaceword = 'geeks for geeks'print(word.rsplit()) # Splits at 'g'. Note that we have# provided maximum limit as 1. So# from right, one splitting happens# and we get \"eeks\" and \"geeks, for, \"word = 'geeks, for, geeks'print(word.rsplit('g', 1)) # Splitting at '@' with maximum splitting# as 1word = 'geeks@for@geeks'print(word.rsplit('@', 1))",
"e": 1136,
"s": 733,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1136,
"text": "Output: "
},
{
"code": null,
"e": 1219,
"s": 1145,
"text": "['geeks', 'for', 'geeks']\n['geeks, for, ', 'eeks']\n['geeks@for', 'geeks']"
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Python3"
},
{
"code": "word = 'geeks, for, geeks, pawan' # maxsplit: 0print(word.rsplit(', ', 0)) # maxsplit: 4print(word.rsplit(', ', 4)) word = 'geeks@for@geeks@for@geeks' # maxsplit: 1print(word.rsplit('@', 1)) # maxsplit: 2print(word.rsplit('@', 2))",
"e": 1463,
"s": 1227,
"text": null
},
{
"code": null,
"e": 1472,
"s": 1463,
"text": "Output: "
},
{
"code": null,
"e": 1605,
"s": 1472,
"text": "['geeks, for, geeks, pawan']\n['geeks', 'for', 'geeks', 'pawan']\n['geeks@for@geeks@for', 'geeks']\n['geeks@for@geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 1613,
"s": 1605,
"text": "Python3"
},
{
"code": "word = 'geeks for geeks' # Since separator is 'None', # so, will be splitted at spaceprint(word.rsplit(None, 1)) print(word.rsplit(None, 2)) # Also observe theseprint('@@@@@geeks@for@geeks'.rsplit('@'))print('@@@@@geeks@for@geeks'.rsplit('@', 1))print('@@@@@geeks@for@geeks'.rsplit('@', 3))print('@@@@@geeks@for@geeks'.rsplit('@', 5))",
"e": 1951,
"s": 1613,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1951,
"text": "Output: "
},
{
"code": null,
"e": 2157,
"s": 1960,
"text": "['geeks for', 'geeks']\n['geeks', 'for', 'geeks']\n['', '', '', '', '', 'geeks', 'for', 'geeks']\n['@@@@@geeks@for', 'geeks']\n['@@@@', 'geeks', 'for', 'geeks']\n['@@', '', '', 'geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 2169,
"s": 2157,
"text": "anikakapoor"
},
{
"code": null,
"e": 2185,
"s": 2169,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 2211,
"s": 2185,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2225,
"s": 2211,
"text": "python-string"
},
{
"code": null,
"e": 2232,
"s": 2225,
"text": "Python"
}
]
|
Smallest window that contains all characters of string itself | 30 May, 2022
Given a string, find the smallest window length with all distinct characters of the given string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca” .Examples:
Input: aabcbcdbca
Output: dbca
Explanation:
Possible substrings= {aabcbcd, abcbcd,
bcdbca, dbca....}
Of the set of possible substrings 'dbca'
is the shortest substring having all the
distinct characters of given string.
Input: aaab
Output: ab
Explanation:
Possible substrings={aaab, aab, ab}
Of the set of possible substrings 'ab'
is the shortest substring having all
the distinct characters of given string.
Solution: Above problem states that we have to find the smallest window that contains all the distinct characters of the given string even if the smallest string contains repeating elements. For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.Method 1: This is the Brute Force method of solving the problem using HashMap.
Approach : For solving the problem we first have to find out all the distinct characters present in the string. This can be done using a HashMap. The next thing is to generate all the possible substrings. This follows by checking whether a substring generated has all the required characters(stored in the hash_map) or not. If yes, then compare its length with the minimum substring length which follows the above constraints, found till now.HashMap: HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles.
Algorithm : Store all distinct characters of the given string in a hash_map.Take a variable count and initialize it with value 0.Generate the substrings using two pointers.Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated.
Store all distinct characters of the given string in a hash_map.Take a variable count and initialize it with value 0.Generate the substrings using two pointers.Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated.
Store all distinct characters of the given string in a hash_map.
Take a variable count and initialize it with value 0.
Generate the substrings using two pointers.
Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated.
As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated.
As soon we find that the character of the substring generated has not been encountered before, increment count by 1.
We can use a visited array of max_chars size to find whether the current character has been encountered before or not.
If count is equal to equal to size of hash_map the substring generated is valid
If it is a valid substring, compare it with the minimum length substring already generated.
Pseudo Code:
maphash_map;
for ( i=0 to str.length())
hash_map[str[i]]++;//finding all distinct characters of string
minimum_size=INT_MAX
Distinct_chars=hash_map.size()
for(i=0 to str.length())
count=0;
sub_str="";
visited[256]={0};
for(j=i to n)
sub_str+=str[j]
if(visited[str[j]]==0)
count++
visited[str[j]]=1;
if(count==Distinct_chars)
end loop
if(sub_str.length()<minimum_size&&
count==Distinct_chars)
ans=sub_str;
return ans
Implementation:
CPP
Java
C#
Python3
Javascript
// C++ program to find the smallest// window containing all characters// of a pattern.#include <bits/stdc++.h>using namespace std; const int MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersstring findSubString(string str){ int n = str.length(); // Count all distinct characters. int dist_count = 0; unordered_map<int, int> hash_map; for (int i = 0; i < n; i++) { hash_map[str[i]]++; } dist_count = hash_map.size(); int size = INT_MAX; string res; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { int count = 0; int visited[256] = { 0 }; string sub_str = ""; for (int j = i; j < n; j++) { if (visited[str[j]] == 0) { count++; visited[str[j]] = 1; } sub_str += str[j]; if (count == dist_count) break; } if (sub_str.length() < size && count == dist_count) { res = sub_str; size=res.length(); } } return res;} // Driver Codeint main(){ string str = "aabcbcdbca"; cout << "Smallest window containing all distinct" " characters is: " << findSubString(str); return 0;}
import java.io.*;import java.util.*; // Java program to find the smallest// window containing all characters// of a pattern.class GFG{ // Function to find smallest window containing // all distinct characters public static String findSubString(String str) { int n = str.length(); // Count all distinct characters. int dist_count = 0; HashMap<Character, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) { if (mp.containsKey(str.charAt(i))) { Integer a = mp.get(str.charAt(i)); mp.put(str.charAt(i),a+1); } else { mp.put(str.charAt(i), 1); } } dist_count = mp.size(); int size = Integer.MAX_VALUE; String res = ""; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { int count = 0; int visited[] = new int[256]; for(int j = 0; j < 256; j++) visited[j] = 0; String sub_str = ""; for (int j = i; j < n; j++) { if (visited[str.charAt(j)] == 0) { count++; visited[str.charAt(j)] = 1; } sub_str += str.charAt(j); if (count == dist_count) break; } if (sub_str.length() < size && count == dist_count) { res = sub_str; size=res.length(); } } return res; } // Driver code public static void main (String[] args) { String str = "aabcbcdbca"; System.out.println("Smallest window containing all distinct"+ " characters is: "+ findSubString(str)) ; }} // This code is contributed by Manu Pathria
// Include namespace systemusing System;using System.Collections.Generic; using System.Collections; // C# program to find the smallest// window containing all characters// of a pattern.public class GFG{ // Function to find smallest window containing // all distinct characters public static String findSubString(String str) { var n = str.Length; // Count all distinct characters. var dist_count = 0; var mp = new Dictionary<char, int>(); for (int i = 0; i < n; i++) { if (mp.ContainsKey(str[i])) { var a = mp[str[i]]; mp[str[i]] = a + 1; } else { mp[str[i]] = 1; } } dist_count = mp.Count; var size = int.MaxValue; var res = ""; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { var count = 0; int[] visited = new int[256]; for (int j = 0; j < 256; j++) { visited[j] = 0; } var sub_str = ""; for (int j = i; j < n; j++) { if (visited[str[j]] == 0) { count++; visited[str[j]] = 1; } sub_str += str[j]; if (count == dist_count) { break; } } if (sub_str.Length < size && count == dist_count) { res = sub_str; size = res.Length; } } return res; } // Driver code public static void Main(String[] args) { var str = "aabcbcdbca"; Console.WriteLine("Smallest window containing all distinct" + " characters is: " + GFG.findSubString(str)); }} // This code is contributed by mukulsomukesh.
# Python3 code for the same approachimport sys MAX_CHARS = 256 # Function to find smallest window containing# all distinct charactersdef findSubString(str): n = len(str) # Count all distinct characters. dist_count = 0 hash_map = {} for i in range(n): if(str[i] in hash_map): hash_map[str[i]] = hash_map[str[i]] + 1 else: hash_map[str[i]] = 1 dist_count = len(hash_map) size = sys.maxsize res = 0 # Now follow the algorithm discussed in below for i in range(n): count = 0 visited= [0]*(MAX_CHARS) sub_str = "" for j in range(i,n): if (visited[ord(str[j])] == 0): count += 1 visited[ord(str[j])] = 1 sub_str += str[j] if (count == dist_count): break if (len(sub_str) < size and count == dist_count): res = sub_str size = len(res) return res # Driver Codestr = "aabcbcdbca"print(f"Smallest window containing all distinct characters is: {findSubString(str)}") # This code is contributed by shinjanpatra.
<script> // JavaScript program to find the smallest// window containing all characters// of a pattern.const MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersfunction findSubString(str){ let n = str.length; // Count all distinct characters. let dist_count = 0; let hash_map = new Map(); for (let i = 0; i < n; i++) { if(hash_map.has(str[i])){ hash_map.set(str[i],hash_map.get(str[i])+1); } else hash_map.set(str[i],1); } dist_count = hash_map.size; let size = Number.MAX_VALUE; let res; // Now follow the algorithm discussed in below for (let i = 0; i < n; i++) { let count = 0; let visited= new Array(MAX_CHARS).fill(0); let sub_str = ""; for (let j = i; j < n; j++) { if (visited[str.charCodeAt(j)] == 0) { count++; visited[str.charCodeAt(j)] = 1; } sub_str += str[j]; if (count == dist_count) break; } if (sub_str.length < size && count == dist_count) { res = sub_str; size = res.length; } } return res;} // Driver Codelet str = "aabcbcdbca";document.write("Smallest window containing all distinct characters is: " + findSubString(str),"</br>"); // This code is contributed by shinjanpatra.</script>
Smallest window containing all distinct characters is: dbca
Complexity Analysis: Time Complexity: O(N^2). This time is required to generate all possible sub-strings of a string of length “N”.Space Complexity: O(N). As a hash_map has been used of size N.
Time Complexity: O(N^2). This time is required to generate all possible sub-strings of a string of length “N”.
Space Complexity: O(N). As a hash_map has been used of size N.
Method 2: Here we have used Sliding Window technique to arrive at the solution. This technique shows how a nested for loop in few problems can be converted to single for loop and hence reducing the time complexity.
Approach: Basically a window of characters is maintained by using two pointers namely start and end. These start and end pointers can be used to shrink and increase the size of window respectively. Whenever the window contains all characters of given string, the window is shrinked from left side to remove extra characters and then its length is compared with the smallest window found so far. If in the present window, no more characters can be deleted then we start increasing the size of the window using the end until all the distinct characters present in the string are also there in the window. Finally, find the minimum size of each window.
Algorithm : Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).Take two pointers start and end which will mark the start and end of window.Take a counter=0 which will be used to count distinct characters in the window.Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.If the counter is equal to total number of distinct characters, Try to shrink the window.For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length.
Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).Take two pointers start and end which will mark the start and end of window.Take a counter=0 which will be used to count distinct characters in the window.Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.If the counter is equal to total number of distinct characters, Try to shrink the window.For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length.
Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).
Take two pointers start and end which will mark the start and end of window.
Take a counter=0 which will be used to count distinct characters in the window.
Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.
If the counter is equal to total number of distinct characters, Try to shrink the window.
For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length.
If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length.
If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.
Now compare the length of present window with the minimum window length.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find the smallest// window containing all characters// of a pattern.#include <bits/stdc++.h>using namespace std; const int MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersstring findSubString(string str){ int n = str.length(); // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; bool visited[MAX_CHARS] = { false }; for (int i = 0; i < n; i++) { if (visited[str[i]] == false) { visited[str[i]] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of characters // that contains all characters of given string. int start = 0, start_index = -1, min_len = INT_MAX; int count = 0; int curr_count[MAX_CHARS] = { 0 }; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str[j]]++; // If any distinct character matched, // then increment count if (curr_count[str[j]] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of times // than its occurrence in pattern, if yes // then remove it from starting and also remove // the useless characters. while (curr_count[str[start]] > 1) { if (curr_count[str[start]] > 1) curr_count[str[start]]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substr(start_index, min_len);} // Driver codeint main(){ string str = "aabcbcdbca"; cout << "Smallest window containing all distinct" " characters is: " << findSubString(str); return 0;}
// Java program to find the smallest window containing// all characters of a pattern.import java.util.Arrays;public class GFG { static final int MAX_CHARS = 256; // Function to find smallest window containing // all distinct characters static String findSubString(String str) { int n = str.length(); // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; boolean[] visited = new boolean[MAX_CHARS]; Arrays.fill(visited, false); for (int i = 0; i < n; i++) { if (visited[str.charAt(i)] == false) { visited[str.charAt(i)] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of // characters that contains all characters of given // string. int start = 0, start_index = -1; int min_len = Integer.MAX_VALUE; int count = 0; int[] curr_count = new int[MAX_CHARS]; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str.charAt(j)]++; // If any distinct character matched, // then increment count if (curr_count[str.charAt(j)] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of // times than its occurrence in pattern, if // yes then remove it from starting and also // remove the useless characters. while (curr_count[str.charAt(start)] > 1) { if (curr_count[str.charAt(start)] > 1) curr_count[str.charAt(start)]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substring(start_index, start_index + min_len); } // Driver code public static void main(String args[]) { String str = "aabcbcdbca"; System.out.println( "Smallest window containing all distinct" + " characters is: " + findSubString(str)); }}// This code is contributed by Sumit Ghosh
# Python program to find the smallest# window containing# all characters of a patternfrom collections import defaultdict MAX_CHARS = 256 # Function to find smallest window# containing all distinct characters def findSubString(strr): n = len(strr) # if string is empty or having one char if n <= 1: return strr # Count all distinct characters. dist_count = len(set([x for x in strr])) curr_count = defaultdict(lambda: 0) count = 0 start = 0 min_len = n # Now follow the algorithm discussed in below # post. We basically maintain a window of characters # that contains all characters of given string. for j in range(n): curr_count[strr[j]] += 1 # If any distinct character matched, # then increment count if curr_count[strr[j]] == 1: count += 1 # Try to minimize the window i.e., check if # any character is occurring more no. of times # than its occurrence in pattern, if yes # then remove it from starting and also remove # the useless characters. if count == dist_count: while curr_count[strr[start]] > 1: if curr_count[strr[start]] > 1: curr_count[strr[start]] -= 1 start += 1 # Update window size len_window = j - start + 1 if min_len > len_window: min_len = len_window start_index = start # Return substring starting from start_index # and length min_len """ return str(strr[start_index: start_index + min_len]) # Driver codeif __name__ == '__main__': print("Smallest window containing " "all distinct characters is: {}".format( findSubString("aabcbcdbca"))) # This code is contributed by# Subhrajit
// C# program to find the smallest window containing// all characters of a pattern.using System; class GFG { static int MAX_CHARS = 256; // Function to find smallest window containing // all distinct characters static string findSubString(string str) { int n = str.Length; // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; bool[] visited = new bool[MAX_CHARS]; for (int i = 0; i < n; i++) { if (visited[str[i]] == false) { visited[str[i]] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of // characters that contains all characters of given // string. int start = 0, start_index = -1, min_len = int.MaxValue; int count = 0; int[] curr_count = new int[MAX_CHARS]; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str[j]]++; // If any distinct character matched, // then increment count if (curr_count[str[j]] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of // times than its occurrence in pattern, if // yes then remove it from starting and also // remove the useless characters. while (curr_count[str[start]] > 1) { if (curr_count[str[start]] > 1) curr_count[str[start]]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.Substring(start_index, min_len); } // Driver code public static void Main(String[] args) { string str = "aabcbcdbca"; Console.WriteLine( "Smallest window containing all distinct" + " characters is: " + findSubString(str)); }} // This code contributed by Rajput-Ji
<script> // JavaScript program to find the smallest// window containing all characters// of a pattern.const MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersfunction findSubString(str){ let n = str.length; // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. let dist_count = 0; let visited = new Array(MAX_CHARS).fill(false); for (let i = 0; i < n; i++) { if (visited[str.charCodeAt(i)] == false) { visited[str.charCodeAt(i)] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of characters // that contains all characters of given string. let start = 0, start_index = -1, min_len = Number.MAX_VALUE; let count = 0; let curr_count = new Array(MAX_CHARS).fill(0); for (let j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str.charCodeAt(j)]++; // If any distinct character matched, // then increment count if (curr_count[str.charCodeAt(j)] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of times // than its occurrence in pattern, if yes // then remove it from starting and also remove // the useless characters. while (curr_count[str.charCodeAt(start)] > 1) { if (curr_count[str.charCodeAt(start)] > 1) curr_count[str.charCodeAt(start)]--; start++; } // Update window size let len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substring(start_index, min_len + start_index);} // Driver codelet str = "aabcbcdbca";document.write("Smallest window containing all distinct characters is: " +findSubString(str),"</br>"); // This code is contributed by shinjanpatra.</script>
Smallest window containing all distinct characters is: dbca
Complexity Analysis: Time Complexity: O(N). As the string is traversed using two pointers only once.Space Complexity: O(N). As a hash_map is used of size N
Time Complexity: O(N). As the string is traversed using two pointers only once.
Space Complexity: O(N). As a hash_map is used of size N
Related Article:
Length of the smallest sub-string consisting of maximum distinct charactershttps://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
Length of the smallest sub-string consisting of maximum distinct characters
https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
This article is contributed by Sahil Chhabra. 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.
Debasish Chowdhury 1
Subhrajit Makur
Rajput-Ji
AakashDkap
bidibaaz123
nikhil4709
sudipasarkar999
manupathria
piyushkumar96
as5853535
amartyaghoshgfg
shinjanpatra
mukulsomukesh
Amazon
Dailyhunt
Microsoft
sliding-window
Arrays
Hash
Strings
Amazon
Microsoft
Dailyhunt
sliding-window
Arrays
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 258,
"s": 52,
"text": "Given a string, find the smallest window length with all distinct characters of the given string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window will be “dbca” .Examples: "
},
{
"code": null,
"e": 680,
"s": 258,
"text": "Input: aabcbcdbca\nOutput: dbca\nExplanation: \nPossible substrings= {aabcbcd, abcbcd, \nbcdbca, dbca....}\nOf the set of possible substrings 'dbca' \nis the shortest substring having all the \ndistinct characters of given string. \n\nInput: aaab\nOutput: ab\nExplanation: \nPossible substrings={aaab, aab, ab}\nOf the set of possible substrings 'ab' \nis the shortest substring having all \nthe distinct characters of given string. "
},
{
"code": null,
"e": 1043,
"s": 680,
"text": "Solution: Above problem states that we have to find the smallest window that contains all the distinct characters of the given string even if the smallest string contains repeating elements. For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.Method 1: This is the Brute Force method of solving the problem using HashMap."
},
{
"code": null,
"e": 2084,
"s": 1043,
"text": "Approach : For solving the problem we first have to find out all the distinct characters present in the string. This can be done using a HashMap. The next thing is to generate all the possible substrings. This follows by checking whether a substring generated has all the required characters(stored in the hash_map) or not. If yes, then compare its length with the minimum substring length which follows the above constraints, found till now.HashMap: HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles. "
},
{
"code": null,
"e": 2717,
"s": 2084,
"text": "Algorithm : Store all distinct characters of the given string in a hash_map.Take a variable count and initialize it with value 0.Generate the substrings using two pointers.Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated."
},
{
"code": null,
"e": 3338,
"s": 2717,
"text": "Store all distinct characters of the given string in a hash_map.Take a variable count and initialize it with value 0.Generate the substrings using two pointers.Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated."
},
{
"code": null,
"e": 3403,
"s": 3338,
"text": "Store all distinct characters of the given string in a hash_map."
},
{
"code": null,
"e": 3457,
"s": 3403,
"text": "Take a variable count and initialize it with value 0."
},
{
"code": null,
"e": 3501,
"s": 3457,
"text": "Generate the substrings using two pointers."
},
{
"code": null,
"e": 3962,
"s": 3501,
"text": "Now check whether generated substring is valid or not-: As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated."
},
{
"code": null,
"e": 4367,
"s": 3962,
"text": "As soon we find that the character of the substring generated has not been encountered before, increment count by 1.We can use a visited array of max_chars size to find whether the current character has been encountered before or not.If count is equal to equal to size of hash_map the substring generated is validIf it is a valid substring, compare it with the minimum length substring already generated."
},
{
"code": null,
"e": 4484,
"s": 4367,
"text": "As soon we find that the character of the substring generated has not been encountered before, increment count by 1."
},
{
"code": null,
"e": 4603,
"s": 4484,
"text": "We can use a visited array of max_chars size to find whether the current character has been encountered before or not."
},
{
"code": null,
"e": 4683,
"s": 4603,
"text": "If count is equal to equal to size of hash_map the substring generated is valid"
},
{
"code": null,
"e": 4775,
"s": 4683,
"text": "If it is a valid substring, compare it with the minimum length substring already generated."
},
{
"code": null,
"e": 4788,
"s": 4775,
"text": "Pseudo Code:"
},
{
"code": null,
"e": 5227,
"s": 4788,
"text": "maphash_map;\nfor ( i=0 to str.length())\nhash_map[str[i]]++;//finding all distinct characters of string\nminimum_size=INT_MAX\nDistinct_chars=hash_map.size()\nfor(i=0 to str.length())\ncount=0;\nsub_str=\"\";\nvisited[256]={0};\n for(j=i to n)\n sub_str+=str[j]\n if(visited[str[j]]==0)\n count++\n visited[str[j]]=1;\n if(count==Distinct_chars)\n end loop\n\nif(sub_str.length()<minimum_size&&\ncount==Distinct_chars)\nans=sub_str;\n \nreturn ans"
},
{
"code": null,
"e": 5243,
"s": 5227,
"text": "Implementation:"
},
{
"code": null,
"e": 5247,
"s": 5243,
"text": "CPP"
},
{
"code": null,
"e": 5252,
"s": 5247,
"text": "Java"
},
{
"code": null,
"e": 5255,
"s": 5252,
"text": "C#"
},
{
"code": null,
"e": 5263,
"s": 5255,
"text": "Python3"
},
{
"code": null,
"e": 5274,
"s": 5263,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest// window containing all characters// of a pattern.#include <bits/stdc++.h>using namespace std; const int MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersstring findSubString(string str){ int n = str.length(); // Count all distinct characters. int dist_count = 0; unordered_map<int, int> hash_map; for (int i = 0; i < n; i++) { hash_map[str[i]]++; } dist_count = hash_map.size(); int size = INT_MAX; string res; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { int count = 0; int visited[256] = { 0 }; string sub_str = \"\"; for (int j = i; j < n; j++) { if (visited[str[j]] == 0) { count++; visited[str[j]] = 1; } sub_str += str[j]; if (count == dist_count) break; } if (sub_str.length() < size && count == dist_count) { res = sub_str; size=res.length(); } } return res;} // Driver Codeint main(){ string str = \"aabcbcdbca\"; cout << \"Smallest window containing all distinct\" \" characters is: \" << findSubString(str); return 0;}",
"e": 6548,
"s": 5274,
"text": null
},
{
"code": "import java.io.*;import java.util.*; // Java program to find the smallest// window containing all characters// of a pattern.class GFG{ // Function to find smallest window containing // all distinct characters public static String findSubString(String str) { int n = str.length(); // Count all distinct characters. int dist_count = 0; HashMap<Character, Integer> mp = new HashMap<>(); for (int i = 0; i < n; i++) { if (mp.containsKey(str.charAt(i))) { Integer a = mp.get(str.charAt(i)); mp.put(str.charAt(i),a+1); } else { mp.put(str.charAt(i), 1); } } dist_count = mp.size(); int size = Integer.MAX_VALUE; String res = \"\"; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { int count = 0; int visited[] = new int[256]; for(int j = 0; j < 256; j++) visited[j] = 0; String sub_str = \"\"; for (int j = i; j < n; j++) { if (visited[str.charAt(j)] == 0) { count++; visited[str.charAt(j)] = 1; } sub_str += str.charAt(j); if (count == dist_count) break; } if (sub_str.length() < size && count == dist_count) { res = sub_str; size=res.length(); } } return res; } // Driver code public static void main (String[] args) { String str = \"aabcbcdbca\"; System.out.println(\"Smallest window containing all distinct\"+ \" characters is: \"+ findSubString(str)) ; }} // This code is contributed by Manu Pathria",
"e": 8454,
"s": 6548,
"text": null
},
{
"code": "// Include namespace systemusing System;using System.Collections.Generic; using System.Collections; // C# program to find the smallest// window containing all characters// of a pattern.public class GFG{ // Function to find smallest window containing // all distinct characters public static String findSubString(String str) { var n = str.Length; // Count all distinct characters. var dist_count = 0; var mp = new Dictionary<char, int>(); for (int i = 0; i < n; i++) { if (mp.ContainsKey(str[i])) { var a = mp[str[i]]; mp[str[i]] = a + 1; } else { mp[str[i]] = 1; } } dist_count = mp.Count; var size = int.MaxValue; var res = \"\"; // Now follow the algorithm discussed in below for (int i = 0; i < n; i++) { var count = 0; int[] visited = new int[256]; for (int j = 0; j < 256; j++) { visited[j] = 0; } var sub_str = \"\"; for (int j = i; j < n; j++) { if (visited[str[j]] == 0) { count++; visited[str[j]] = 1; } sub_str += str[j]; if (count == dist_count) { break; } } if (sub_str.Length < size && count == dist_count) { res = sub_str; size = res.Length; } } return res; } // Driver code public static void Main(String[] args) { var str = \"aabcbcdbca\"; Console.WriteLine(\"Smallest window containing all distinct\" + \" characters is: \" + GFG.findSubString(str)); }} // This code is contributed by mukulsomukesh.",
"e": 10377,
"s": 8454,
"text": null
},
{
"code": "# Python3 code for the same approachimport sys MAX_CHARS = 256 # Function to find smallest window containing# all distinct charactersdef findSubString(str): n = len(str) # Count all distinct characters. dist_count = 0 hash_map = {} for i in range(n): if(str[i] in hash_map): hash_map[str[i]] = hash_map[str[i]] + 1 else: hash_map[str[i]] = 1 dist_count = len(hash_map) size = sys.maxsize res = 0 # Now follow the algorithm discussed in below for i in range(n): count = 0 visited= [0]*(MAX_CHARS) sub_str = \"\" for j in range(i,n): if (visited[ord(str[j])] == 0): count += 1 visited[ord(str[j])] = 1 sub_str += str[j] if (count == dist_count): break if (len(sub_str) < size and count == dist_count): res = sub_str size = len(res) return res # Driver Codestr = \"aabcbcdbca\"print(f\"Smallest window containing all distinct characters is: {findSubString(str)}\") # This code is contributed by shinjanpatra.",
"e": 11432,
"s": 10377,
"text": null
},
{
"code": "<script> // JavaScript program to find the smallest// window containing all characters// of a pattern.const MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersfunction findSubString(str){ let n = str.length; // Count all distinct characters. let dist_count = 0; let hash_map = new Map(); for (let i = 0; i < n; i++) { if(hash_map.has(str[i])){ hash_map.set(str[i],hash_map.get(str[i])+1); } else hash_map.set(str[i],1); } dist_count = hash_map.size; let size = Number.MAX_VALUE; let res; // Now follow the algorithm discussed in below for (let i = 0; i < n; i++) { let count = 0; let visited= new Array(MAX_CHARS).fill(0); let sub_str = \"\"; for (let j = i; j < n; j++) { if (visited[str.charCodeAt(j)] == 0) { count++; visited[str.charCodeAt(j)] = 1; } sub_str += str[j]; if (count == dist_count) break; } if (sub_str.length < size && count == dist_count) { res = sub_str; size = res.length; } } return res;} // Driver Codelet str = \"aabcbcdbca\";document.write(\"Smallest window containing all distinct characters is: \" + findSubString(str),\"</br>\"); // This code is contributed by shinjanpatra.</script>",
"e": 12814,
"s": 11432,
"text": null
},
{
"code": null,
"e": 12874,
"s": 12814,
"text": "Smallest window containing all distinct characters is: dbca"
},
{
"code": null,
"e": 13068,
"s": 12874,
"text": "Complexity Analysis: Time Complexity: O(N^2). This time is required to generate all possible sub-strings of a string of length “N”.Space Complexity: O(N). As a hash_map has been used of size N."
},
{
"code": null,
"e": 13179,
"s": 13068,
"text": "Time Complexity: O(N^2). This time is required to generate all possible sub-strings of a string of length “N”."
},
{
"code": null,
"e": 13242,
"s": 13179,
"text": "Space Complexity: O(N). As a hash_map has been used of size N."
},
{
"code": null,
"e": 13457,
"s": 13242,
"text": "Method 2: Here we have used Sliding Window technique to arrive at the solution. This technique shows how a nested for loop in few problems can be converted to single for loop and hence reducing the time complexity."
},
{
"code": null,
"e": 14107,
"s": 13457,
"text": "Approach: Basically a window of characters is maintained by using two pointers namely start and end. These start and end pointers can be used to shrink and increase the size of window respectively. Whenever the window contains all characters of given string, the window is shrinked from left side to remove extra characters and then its length is compared with the smallest window found so far. If in the present window, no more characters can be deleted then we start increasing the size of the window using the end until all the distinct characters present in the string are also there in the window. Finally, find the minimum size of each window."
},
{
"code": null,
"e": 14919,
"s": 14107,
"text": "Algorithm : Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).Take two pointers start and end which will mark the start and end of window.Take a counter=0 which will be used to count distinct characters in the window.Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.If the counter is equal to total number of distinct characters, Try to shrink the window.For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length."
},
{
"code": null,
"e": 15719,
"s": 14919,
"text": "Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string).Take two pointers start and end which will mark the start and end of window.Take a counter=0 which will be used to count distinct characters in the window.Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1.If the counter is equal to total number of distinct characters, Try to shrink the window.For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length."
},
{
"code": null,
"e": 15924,
"s": 15719,
"text": "Maintain an array (visited) of maximum possible characters (256 characters) and as soon as we find any in the string, mark that index in the array (this is to count all distinct characters in the string)."
},
{
"code": null,
"e": 16001,
"s": 15924,
"text": "Take two pointers start and end which will mark the start and end of window."
},
{
"code": null,
"e": 16081,
"s": 16001,
"text": "Take a counter=0 which will be used to count distinct characters in the window."
},
{
"code": null,
"e": 16227,
"s": 16081,
"text": "Now start reading the characters of the given string and if we come across a character which has not been visited yet increment the counter by 1."
},
{
"code": null,
"e": 16317,
"s": 16227,
"text": "If the counter is equal to total number of distinct characters, Try to shrink the window."
},
{
"code": null,
"e": 16524,
"s": 16317,
"text": "For shrinking the window -: If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length."
},
{
"code": null,
"e": 16703,
"s": 16524,
"text": "If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant.Now compare the length of present window with the minimum window length."
},
{
"code": null,
"e": 16810,
"s": 16703,
"text": "If the frequency of character at start pointer is greater than 1 increment the pointer as it is redundant."
},
{
"code": null,
"e": 16883,
"s": 16810,
"text": "Now compare the length of present window with the minimum window length."
},
{
"code": null,
"e": 16899,
"s": 16883,
"text": "Implementation:"
},
{
"code": null,
"e": 16903,
"s": 16899,
"text": "C++"
},
{
"code": null,
"e": 16908,
"s": 16903,
"text": "Java"
},
{
"code": null,
"e": 16916,
"s": 16908,
"text": "Python3"
},
{
"code": null,
"e": 16919,
"s": 16916,
"text": "C#"
},
{
"code": null,
"e": 16930,
"s": 16919,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest// window containing all characters// of a pattern.#include <bits/stdc++.h>using namespace std; const int MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersstring findSubString(string str){ int n = str.length(); // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; bool visited[MAX_CHARS] = { false }; for (int i = 0; i < n; i++) { if (visited[str[i]] == false) { visited[str[i]] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of characters // that contains all characters of given string. int start = 0, start_index = -1, min_len = INT_MAX; int count = 0; int curr_count[MAX_CHARS] = { 0 }; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str[j]]++; // If any distinct character matched, // then increment count if (curr_count[str[j]] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of times // than its occurrence in pattern, if yes // then remove it from starting and also remove // the useless characters. while (curr_count[str[start]] > 1) { if (curr_count[str[start]] > 1) curr_count[str[start]]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substr(start_index, min_len);} // Driver codeint main(){ string str = \"aabcbcdbca\"; cout << \"Smallest window containing all distinct\" \" characters is: \" << findSubString(str); return 0;}",
"e": 19104,
"s": 16930,
"text": null
},
{
"code": "// Java program to find the smallest window containing// all characters of a pattern.import java.util.Arrays;public class GFG { static final int MAX_CHARS = 256; // Function to find smallest window containing // all distinct characters static String findSubString(String str) { int n = str.length(); // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; boolean[] visited = new boolean[MAX_CHARS]; Arrays.fill(visited, false); for (int i = 0; i < n; i++) { if (visited[str.charAt(i)] == false) { visited[str.charAt(i)] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of // characters that contains all characters of given // string. int start = 0, start_index = -1; int min_len = Integer.MAX_VALUE; int count = 0; int[] curr_count = new int[MAX_CHARS]; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str.charAt(j)]++; // If any distinct character matched, // then increment count if (curr_count[str.charAt(j)] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of // times than its occurrence in pattern, if // yes then remove it from starting and also // remove the useless characters. while (curr_count[str.charAt(start)] > 1) { if (curr_count[str.charAt(start)] > 1) curr_count[str.charAt(start)]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substring(start_index, start_index + min_len); } // Driver code public static void main(String args[]) { String str = \"aabcbcdbca\"; System.out.println( \"Smallest window containing all distinct\" + \" characters is: \" + findSubString(str)); }}// This code is contributed by Sumit Ghosh",
"e": 21780,
"s": 19104,
"text": null
},
{
"code": "# Python program to find the smallest# window containing# all characters of a patternfrom collections import defaultdict MAX_CHARS = 256 # Function to find smallest window# containing all distinct characters def findSubString(strr): n = len(strr) # if string is empty or having one char if n <= 1: return strr # Count all distinct characters. dist_count = len(set([x for x in strr])) curr_count = defaultdict(lambda: 0) count = 0 start = 0 min_len = n # Now follow the algorithm discussed in below # post. We basically maintain a window of characters # that contains all characters of given string. for j in range(n): curr_count[strr[j]] += 1 # If any distinct character matched, # then increment count if curr_count[strr[j]] == 1: count += 1 # Try to minimize the window i.e., check if # any character is occurring more no. of times # than its occurrence in pattern, if yes # then remove it from starting and also remove # the useless characters. if count == dist_count: while curr_count[strr[start]] > 1: if curr_count[strr[start]] > 1: curr_count[strr[start]] -= 1 start += 1 # Update window size len_window = j - start + 1 if min_len > len_window: min_len = len_window start_index = start # Return substring starting from start_index # and length min_len \"\"\" return str(strr[start_index: start_index + min_len]) # Driver codeif __name__ == '__main__': print(\"Smallest window containing \" \"all distinct characters is: {}\".format( findSubString(\"aabcbcdbca\"))) # This code is contributed by# Subhrajit",
"e": 23601,
"s": 21780,
"text": null
},
{
"code": "// C# program to find the smallest window containing// all characters of a pattern.using System; class GFG { static int MAX_CHARS = 256; // Function to find smallest window containing // all distinct characters static string findSubString(string str) { int n = str.Length; // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. int dist_count = 0; bool[] visited = new bool[MAX_CHARS]; for (int i = 0; i < n; i++) { if (visited[str[i]] == false) { visited[str[i]] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of // characters that contains all characters of given // string. int start = 0, start_index = -1, min_len = int.MaxValue; int count = 0; int[] curr_count = new int[MAX_CHARS]; for (int j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str[j]]++; // If any distinct character matched, // then increment count if (curr_count[str[j]] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of // times than its occurrence in pattern, if // yes then remove it from starting and also // remove the useless characters. while (curr_count[str[start]] > 1) { if (curr_count[str[start]] > 1) curr_count[str[start]]--; start++; } // Update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.Substring(start_index, min_len); } // Driver code public static void Main(String[] args) { string str = \"aabcbcdbca\"; Console.WriteLine( \"Smallest window containing all distinct\" + \" characters is: \" + findSubString(str)); }} // This code contributed by Rajput-Ji",
"e": 26107,
"s": 23601,
"text": null
},
{
"code": "<script> // JavaScript program to find the smallest// window containing all characters// of a pattern.const MAX_CHARS = 256; // Function to find smallest window containing// all distinct charactersfunction findSubString(str){ let n = str.length; // if string is empty or having one char if (n <= 1) return str; // Count all distinct characters. let dist_count = 0; let visited = new Array(MAX_CHARS).fill(false); for (let i = 0; i < n; i++) { if (visited[str.charCodeAt(i)] == false) { visited[str.charCodeAt(i)] = true; dist_count++; } } // Now follow the algorithm discussed in below // post. We basically maintain a window of characters // that contains all characters of given string. let start = 0, start_index = -1, min_len = Number.MAX_VALUE; let count = 0; let curr_count = new Array(MAX_CHARS).fill(0); for (let j = 0; j < n; j++) { // Count occurrence of characters of string curr_count[str.charCodeAt(j)]++; // If any distinct character matched, // then increment count if (curr_count[str.charCodeAt(j)] == 1) count++; // if all the characters are matched if (count == dist_count) { // Try to minimize the window i.e., check if // any character is occurring more no. of times // than its occurrence in pattern, if yes // then remove it from starting and also remove // the useless characters. while (curr_count[str.charCodeAt(start)] > 1) { if (curr_count[str.charCodeAt(start)] > 1) curr_count[str.charCodeAt(start)]--; start++; } // Update window size let len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // Return substring starting from start_index // and length min_len return str.substring(start_index, min_len + start_index);} // Driver codelet str = \"aabcbcdbca\";document.write(\"Smallest window containing all distinct characters is: \" +findSubString(str),\"</br>\"); // This code is contributed by shinjanpatra.</script>",
"e": 28377,
"s": 26107,
"text": null
},
{
"code": null,
"e": 28437,
"s": 28377,
"text": "Smallest window containing all distinct characters is: dbca"
},
{
"code": null,
"e": 28593,
"s": 28437,
"text": "Complexity Analysis: Time Complexity: O(N). As the string is traversed using two pointers only once.Space Complexity: O(N). As a hash_map is used of size N"
},
{
"code": null,
"e": 28673,
"s": 28593,
"text": "Time Complexity: O(N). As the string is traversed using two pointers only once."
},
{
"code": null,
"e": 28729,
"s": 28673,
"text": "Space Complexity: O(N). As a hash_map is used of size N"
},
{
"code": null,
"e": 28747,
"s": 28729,
"text": "Related Article: "
},
{
"code": null,
"e": 28934,
"s": 28747,
"text": "Length of the smallest sub-string consisting of maximum distinct charactershttps://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/"
},
{
"code": null,
"e": 29010,
"s": 28934,
"text": "Length of the smallest sub-string consisting of maximum distinct characters"
},
{
"code": null,
"e": 29122,
"s": 29010,
"text": "https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/"
},
{
"code": null,
"e": 29549,
"s": 29122,
"text": "This article is contributed by Sahil Chhabra. 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. "
},
{
"code": null,
"e": 29570,
"s": 29549,
"text": "Debasish Chowdhury 1"
},
{
"code": null,
"e": 29586,
"s": 29570,
"text": "Subhrajit Makur"
},
{
"code": null,
"e": 29596,
"s": 29586,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29607,
"s": 29596,
"text": "AakashDkap"
},
{
"code": null,
"e": 29619,
"s": 29607,
"text": "bidibaaz123"
},
{
"code": null,
"e": 29630,
"s": 29619,
"text": "nikhil4709"
},
{
"code": null,
"e": 29646,
"s": 29630,
"text": "sudipasarkar999"
},
{
"code": null,
"e": 29658,
"s": 29646,
"text": "manupathria"
},
{
"code": null,
"e": 29672,
"s": 29658,
"text": "piyushkumar96"
},
{
"code": null,
"e": 29682,
"s": 29672,
"text": "as5853535"
},
{
"code": null,
"e": 29698,
"s": 29682,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 29711,
"s": 29698,
"text": "shinjanpatra"
},
{
"code": null,
"e": 29725,
"s": 29711,
"text": "mukulsomukesh"
},
{
"code": null,
"e": 29732,
"s": 29725,
"text": "Amazon"
},
{
"code": null,
"e": 29742,
"s": 29732,
"text": "Dailyhunt"
},
{
"code": null,
"e": 29752,
"s": 29742,
"text": "Microsoft"
},
{
"code": null,
"e": 29767,
"s": 29752,
"text": "sliding-window"
},
{
"code": null,
"e": 29774,
"s": 29767,
"text": "Arrays"
},
{
"code": null,
"e": 29779,
"s": 29774,
"text": "Hash"
},
{
"code": null,
"e": 29787,
"s": 29779,
"text": "Strings"
},
{
"code": null,
"e": 29794,
"s": 29787,
"text": "Amazon"
},
{
"code": null,
"e": 29804,
"s": 29794,
"text": "Microsoft"
},
{
"code": null,
"e": 29814,
"s": 29804,
"text": "Dailyhunt"
},
{
"code": null,
"e": 29829,
"s": 29814,
"text": "sliding-window"
},
{
"code": null,
"e": 29836,
"s": 29829,
"text": "Arrays"
},
{
"code": null,
"e": 29841,
"s": 29836,
"text": "Hash"
},
{
"code": null,
"e": 29849,
"s": 29841,
"text": "Strings"
},
{
"code": null,
"e": 29947,
"s": 29849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29962,
"s": 29947,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30008,
"s": 29962,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30076,
"s": 30008,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 30120,
"s": 30076,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 30152,
"s": 30120,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 30237,
"s": 30152,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 30275,
"s": 30237,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 30311,
"s": 30275,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 30342,
"s": 30311,
"text": "Hashing | Set 1 (Introduction)"
}
]
|
Python | How to use Multiple kv files in kivy | 07 Feb, 2020
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
In this article, we will see how can we use multiple .kv files in a single Application .
This is the Python program, which uses GridLayout as the root widget. In addition to the main kv file, it loads box1.kv, box2.kv and box3.kv. There are also 2 application variables. These variables are referenced from the main kv file.
Kivy Tutorial – Learn Kivy with Examples.
Basic Approach:
1) import kivy
2) import kivyApp
3) import Gridlayout
4) import Builder
5) Set minimum version(optional)
6) Create Layout class
7) Create App class
8) Set up multiple .kv file
9) return Layout/widget/Class(according to requirement)
10) Run an instance of the class
main.py file of the implementation:
# Multiple .kv file Python code import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The GridLayout arranges children in a matrix.# It takes the available space and divides# it into columns and rows, then adds# widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Builder is a global Kivy instance used# in widgets that you can use to load other# kv files in addition to the default ones.from kivy.lang import Builder # Loading Multiple .kv files Builder.load_file('box1.kv')Builder.load_file('box2.kv')Builder.load_file('box3.kv') # Creating main kv file classclass main_kv(GridLayout): pass # Create App classclass MainApp(App): def build(self): self.x = 150 self.y = 400 return main_kv() # run the Appif __name__=='__main__': MainApp().run()
The main kv file contains a GridLayout with 3 columns. These 3 Columns contains different AnchorLayouts. These all are defined in the main.kv file.
Now the main.kv file:
# Creating the main .kv files# the difference is that it is# the heart of the Application# Other are just Organs <main_kv>: # Assigning Grids cols: 3 # Creating AnchorLayout AnchorLayout: anchor_x: 'left' anchor_y: 'center' # Canvas creation canvas: Color: rgb: [1, 0, 0] Rectangle: pos: self.pos size: self.size Box1: size_hint: [None, None] size: [app.x, app.y] AnchorLayout: anchor_x: 'center' anchor_y: 'center' canvas: Color: rgb: [0, 1, 0] Rectangle: pos: self.pos size: self.size Box2: size_hint: [None, None] size: [app.x, app.y] AnchorLayout: anchor_x: 'right' anchor_y: 'center' canvas: Color: rgb: [0, 0, 1] Rectangle: pos: self.pos size: self.size Box3: size_hint: [None, None] size: [app.x, app.y]
Now as shown in the Outputs there are different buttons in each grid to create Buttonsin every grid we are using Different .kv files.
box1.kv file –
# Creating 1st .kv file <Box1@BoxLayout>: Button: text: 'B1a' Button: text: 'B1b'
box2.kv file –
# Creating 2nd .kv file <Box2@BoxLayout>: Button: text: 'B2a' Button: text: 'B2b'
box3.kv file –
# Creating 3rd .kv file <Box3@BoxLayout>: Button: text: 'B3a' Button: text: 'B3b'
Output :
Python-gui
Python-kivy
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 353,
"s": 264,
"text": "In this article, we will see how can we use multiple .kv files in a single Application ."
},
{
"code": null,
"e": 589,
"s": 353,
"text": "This is the Python program, which uses GridLayout as the root widget. In addition to the main kv file, it loads box1.kv, box2.kv and box3.kv. There are also 2 application variables. These variables are referenced from the main kv file."
},
{
"code": null,
"e": 632,
"s": 589,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 914,
"s": 632,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Gridlayout\n4) import Builder\n5) Set minimum version(optional)\n6) Create Layout class\n7) Create App class\n8) Set up multiple .kv file\n9) return Layout/widget/Class(according to requirement)\n10) Run an instance of the class"
},
{
"code": null,
"e": 950,
"s": 914,
"text": "main.py file of the implementation:"
},
{
"code": "# Multiple .kv file Python code import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The GridLayout arranges children in a matrix.# It takes the available space and divides# it into columns and rows, then adds# widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Builder is a global Kivy instance used# in widgets that you can use to load other# kv files in addition to the default ones.from kivy.lang import Builder # Loading Multiple .kv files Builder.load_file('box1.kv')Builder.load_file('box2.kv')Builder.load_file('box3.kv') # Creating main kv file classclass main_kv(GridLayout): pass # Create App classclass MainApp(App): def build(self): self.x = 150 self.y = 400 return main_kv() # run the Appif __name__=='__main__': MainApp().run()",
"e": 1864,
"s": 950,
"text": null
},
{
"code": null,
"e": 2012,
"s": 1864,
"text": "The main kv file contains a GridLayout with 3 columns. These 3 Columns contains different AnchorLayouts. These all are defined in the main.kv file."
},
{
"code": null,
"e": 2034,
"s": 2012,
"text": "Now the main.kv file:"
},
{
"code": "# Creating the main .kv files# the difference is that it is# the heart of the Application# Other are just Organs <main_kv>: # Assigning Grids cols: 3 # Creating AnchorLayout AnchorLayout: anchor_x: 'left' anchor_y: 'center' # Canvas creation canvas: Color: rgb: [1, 0, 0] Rectangle: pos: self.pos size: self.size Box1: size_hint: [None, None] size: [app.x, app.y] AnchorLayout: anchor_x: 'center' anchor_y: 'center' canvas: Color: rgb: [0, 1, 0] Rectangle: pos: self.pos size: self.size Box2: size_hint: [None, None] size: [app.x, app.y] AnchorLayout: anchor_x: 'right' anchor_y: 'center' canvas: Color: rgb: [0, 0, 1] Rectangle: pos: self.pos size: self.size Box3: size_hint: [None, None] size: [app.x, app.y] ",
"e": 3143,
"s": 2034,
"text": null
},
{
"code": null,
"e": 3277,
"s": 3143,
"text": "Now as shown in the Outputs there are different buttons in each grid to create Buttonsin every grid we are using Different .kv files."
},
{
"code": null,
"e": 3292,
"s": 3277,
"text": "box1.kv file –"
},
{
"code": "# Creating 1st .kv file <Box1@BoxLayout>: Button: text: 'B1a' Button: text: 'B1b'",
"e": 3397,
"s": 3292,
"text": null
},
{
"code": null,
"e": 3412,
"s": 3397,
"text": "box2.kv file –"
},
{
"code": "# Creating 2nd .kv file <Box2@BoxLayout>: Button: text: 'B2a' Button: text: 'B2b'",
"e": 3515,
"s": 3412,
"text": null
},
{
"code": null,
"e": 3530,
"s": 3515,
"text": "box3.kv file –"
},
{
"code": "# Creating 3rd .kv file <Box3@BoxLayout>: Button: text: 'B3a' Button: text: 'B3b'",
"e": 3634,
"s": 3530,
"text": null
},
{
"code": null,
"e": 3643,
"s": 3634,
"text": "Output :"
},
{
"code": null,
"e": 3654,
"s": 3643,
"text": "Python-gui"
},
{
"code": null,
"e": 3666,
"s": 3654,
"text": "Python-kivy"
},
{
"code": null,
"e": 3673,
"s": 3666,
"text": "Python"
},
{
"code": null,
"e": 3771,
"s": 3673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3789,
"s": 3771,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3831,
"s": 3789,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3853,
"s": 3831,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3879,
"s": 3853,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3911,
"s": 3879,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3940,
"s": 3911,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3967,
"s": 3940,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3988,
"s": 3967,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4024,
"s": 3988,
"text": "Convert integer to string in Python"
}
]
|
Python OpenCV – Pose Estimation | 18 Jul, 2021
Pose estimation is a computer vision technique that is used to predict the configuration of the body(POSE) from an image. The reason for its importance is the abundance of applications that can benefit from technology.
Human pose estimation localizes body key points to accurately recognize the postures of individuals given an image. These estimations are performed in either 3D or 2D.
The main process of human pose estimation includes two basic steps: i) localizing human body joints/key points ii) grouping those joints into valid human pose configuration
In the first step, the main focus is on finding the location of each key points of human beings. E.g. Head, shoulder, arm, hand, knee, ankle. The second step is grouping those joints into valid human pose configuration which determines the pairwise terms between body parts.
Fig(b) represents detecting the key points and Fig(a) represents grouping of key points
OpenCV Python is a library of Python bindings designed to solve computer vision problems. It mainly focuses on image processing, video capture and analysis including features like face detection and object detection.
OpenCV Python is nothing but a wrapper class for the original C++ library to be used with Python. Using this, all the OpenCV array structures gets converted to/from NumPy arrays. This makes it easier to integrate it with other libraries which use NumPy. For example, libraries such as SciPy and Matplotlib.
To know more about OpenCV, https://opencv.org/about/
In datasets selection, COCO and MPII are default picks in recent cases. Especially, COCO is a famous dataset by its property of having very wide human poses and an enormous number of images. LSP and FLIC datasets are also used next to COCO and MPII.
http://cocodataset.org/#keypoints-2018
http://human-pose.mpi-inf.mpg.de/
http://www.robots.ox.ac.uk/~vgg/data/pose_evaluation/
You can download the model weight files using the scripts provided at this location.
In this section, we will see how to load the trained models in OpenCV and check the outputs. We will discuss code for only single person pose estimation to keep things simple. These outputs can be used to find the pose for every person in a frame if multiple people are present. We will cover the multiple-person case in a future post.
First, download the code and model files from below. There are separate files for Image and Video inputs. Please go through the README file if you encounter any difficulty in running the code.
Use the getModels.sh file provided with the code to download all the model weights to the respective folders. Note that the configuration proto files are already present in the folders.
Python3
sudo chmod a+x getModels.sh./getModels.sh
Check the folders to ensure that the model binaries (.caffemodel files) have been downloaded. If you are not able to run the above script, then you can download the model by clicking here for the MPII model and here for COCO model.
We are using models trained on Caffe Deep Learning Framework. Caffe models have 2 files –
prototxt file which specifies the architecture of the neural network — how the different layers are arranged etc.caffemodel file which stores the weights of the trained model
prototxt file which specifies the architecture of the neural network — how the different layers are arranged etc.
caffemodel file which stores the weights of the trained model
We will use these two files to load the network into memory.
Python3
# Specify the paths for the 2 filesprotoFile = "pose/mpi/pose_deploy_linevec_faster_4_stages.prototxt"weightsFile = "pose/mpi/pose_iter_160000.caffemodel"# Read the network into Memorynet = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)
The input frame that we read using OpenCV should be converted to an input blob (like Caffe) so that it can be fed to the network. This is done using the blobFromImage function which converts the image from OpenCV format to Caffe blob format.
The parameters are to be provided in the blobFromImage function. First, we normalize the pixel values to be in (0,1). Then we specify the dimensions of the image. Next, the Mean value to be subtracted, which is (0,0,0). There is no need to swap the R and B channels since both OpenCV and Caffe use RGB format.
Python3
# Read imageframe = cv2.imread("single.jpg") # Specify the input image dimensionsinWidth = 368inHeight = 368 # Prepare the frame to be fed to the networkinpBlob = cv2.dnn.blobFromImage( frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) # Set the prepared object as the input blob of the networknet.setInput(inpBlob)
Python3
output = net.forward()
The output is a 4D matrix :
The first dimension being the image ID ()in case you pass more than one image to the network).The second dimension indicates the index of a key point. The model produces Confidence Maps and Part Affinity maps which are all concatenated. For COCO model it consists of 57 parts — 18 key point confidence Maps + 1 background + 19*2 Part Affinity Maps. Similarly, for MPII, it produces 44 points. We will be using only the first few points which correspond to Key points.The third dimension is the height of the output map.The fourth dimension is the width of the output map.
The first dimension being the image ID ()in case you pass more than one image to the network).
The second dimension indicates the index of a key point. The model produces Confidence Maps and Part Affinity maps which are all concatenated. For COCO model it consists of 57 parts — 18 key point confidence Maps + 1 background + 19*2 Part Affinity Maps. Similarly, for MPII, it produces 44 points. We will be using only the first few points which correspond to Key points.
The third dimension is the height of the output map.
The fourth dimension is the width of the output map.
Once the key points are detected, we just plot them on the image.
Python3
H = out.shape[2]W = out.shape[3]# Empty list to store the detected keypointspoints = []for i in range(len()): # confidence map of corresponding body's part. probMap = output[0, i, :, :] # Find global maxima of the probMap. minVal, prob, minLoc, point = cv2.minMaxLoc(probMap) # Scale the point to fit on the original image x = (frameWidth * point[0]) / W y = (frameHeight * point[1]) / H if prob > threshold: cv2.circle(frame, (int(x), int(y)), 15, (0, 255, 255), thickness=-1, lineType=cv.FILLED) cv2.putText(frame, "{}".format(i), (int(x), int( y)), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, lineType=cv2.LINE_AA) # Add the point to the list if the probability is greater than the threshold points.append((int(x), int(y))) else: points.append(None) cv2.imshow("Output-Keypoints", frame)cv2.waitKey(0)cv2.destroyAllWindows()
Fig(a) shows the key points plotted using COCO model. Fig(b) shows the key points plotted using MPII model.
This figure shows the skeleton formed by all the key points joined
Python3
for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if points[partA] and points[partB]: cv2.line(frameCopy, points[partA], points[partB], (0, 255, 0), 3)
We found that COCO model is 1.5 times slower than the MPI model.
Sign languages to help disabled people.
Human tracking
Gaming
Video surveillance
Advanced Driver Assistance Systems (ADAS)
Action recognition
https://github.com/CMU-Perceptual-Computing-Lab/openpose
https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/
https://ieeexplore.ieee.org/document/9144178
Deep-Learning
OpenCV
Picked
Machine Learning
Project
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": "\n18 Jul, 2021"
},
{
"code": null,
"e": 274,
"s": 54,
"text": "Pose estimation is a computer vision technique that is used to predict the configuration of the body(POSE) from an image. The reason for its importance is the abundance of applications that can benefit from technology. "
},
{
"code": null,
"e": 443,
"s": 274,
"text": "Human pose estimation localizes body key points to accurately recognize the postures of individuals given an image. These estimations are performed in either 3D or 2D. "
},
{
"code": null,
"e": 828,
"s": 443,
"text": "The main process of human pose estimation includes two basic steps: i) localizing human body joints/key points ii) grouping those joints into valid human pose configuration"
},
{
"code": null,
"e": 1103,
"s": 828,
"text": "In the first step, the main focus is on finding the location of each key points of human beings. E.g. Head, shoulder, arm, hand, knee, ankle. The second step is grouping those joints into valid human pose configuration which determines the pairwise terms between body parts."
},
{
"code": null,
"e": 1191,
"s": 1103,
"text": "Fig(b) represents detecting the key points and Fig(a) represents grouping of key points"
},
{
"code": null,
"e": 1410,
"s": 1191,
"text": "OpenCV Python is a library of Python bindings designed to solve computer vision problems. It mainly focuses on image processing, video capture and analysis including features like face detection and object detection. "
},
{
"code": null,
"e": 1717,
"s": 1410,
"text": "OpenCV Python is nothing but a wrapper class for the original C++ library to be used with Python. Using this, all the OpenCV array structures gets converted to/from NumPy arrays. This makes it easier to integrate it with other libraries which use NumPy. For example, libraries such as SciPy and Matplotlib."
},
{
"code": null,
"e": 1770,
"s": 1717,
"text": "To know more about OpenCV, https://opencv.org/about/"
},
{
"code": null,
"e": 2020,
"s": 1770,
"text": "In datasets selection, COCO and MPII are default picks in recent cases. Especially, COCO is a famous dataset by its property of having very wide human poses and an enormous number of images. LSP and FLIC datasets are also used next to COCO and MPII."
},
{
"code": null,
"e": 2059,
"s": 2020,
"text": "http://cocodataset.org/#keypoints-2018"
},
{
"code": null,
"e": 2093,
"s": 2059,
"text": "http://human-pose.mpi-inf.mpg.de/"
},
{
"code": null,
"e": 2147,
"s": 2093,
"text": "http://www.robots.ox.ac.uk/~vgg/data/pose_evaluation/"
},
{
"code": null,
"e": 2232,
"s": 2147,
"text": "You can download the model weight files using the scripts provided at this location."
},
{
"code": null,
"e": 2568,
"s": 2232,
"text": "In this section, we will see how to load the trained models in OpenCV and check the outputs. We will discuss code for only single person pose estimation to keep things simple. These outputs can be used to find the pose for every person in a frame if multiple people are present. We will cover the multiple-person case in a future post."
},
{
"code": null,
"e": 2761,
"s": 2568,
"text": "First, download the code and model files from below. There are separate files for Image and Video inputs. Please go through the README file if you encounter any difficulty in running the code."
},
{
"code": null,
"e": 2947,
"s": 2761,
"text": "Use the getModels.sh file provided with the code to download all the model weights to the respective folders. Note that the configuration proto files are already present in the folders."
},
{
"code": null,
"e": 2955,
"s": 2947,
"text": "Python3"
},
{
"code": "sudo chmod a+x getModels.sh./getModels.sh",
"e": 2997,
"s": 2955,
"text": null
},
{
"code": null,
"e": 3277,
"s": 2997,
"text": "Check the folders to ensure that the model binaries (.caffemodel files) have been downloaded. If you are not able to run the above script, then you can download the model by clicking here for the MPII model and here for COCO model."
},
{
"code": null,
"e": 3367,
"s": 3277,
"text": "We are using models trained on Caffe Deep Learning Framework. Caffe models have 2 files –"
},
{
"code": null,
"e": 3542,
"s": 3367,
"text": "prototxt file which specifies the architecture of the neural network — how the different layers are arranged etc.caffemodel file which stores the weights of the trained model"
},
{
"code": null,
"e": 3656,
"s": 3542,
"text": "prototxt file which specifies the architecture of the neural network — how the different layers are arranged etc."
},
{
"code": null,
"e": 3718,
"s": 3656,
"text": "caffemodel file which stores the weights of the trained model"
},
{
"code": null,
"e": 3779,
"s": 3718,
"text": "We will use these two files to load the network into memory."
},
{
"code": null,
"e": 3787,
"s": 3779,
"text": "Python3"
},
{
"code": "# Specify the paths for the 2 filesprotoFile = \"pose/mpi/pose_deploy_linevec_faster_4_stages.prototxt\"weightsFile = \"pose/mpi/pose_iter_160000.caffemodel\"# Read the network into Memorynet = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)",
"e": 4026,
"s": 3787,
"text": null
},
{
"code": null,
"e": 4268,
"s": 4026,
"text": "The input frame that we read using OpenCV should be converted to an input blob (like Caffe) so that it can be fed to the network. This is done using the blobFromImage function which converts the image from OpenCV format to Caffe blob format."
},
{
"code": null,
"e": 4578,
"s": 4268,
"text": "The parameters are to be provided in the blobFromImage function. First, we normalize the pixel values to be in (0,1). Then we specify the dimensions of the image. Next, the Mean value to be subtracted, which is (0,0,0). There is no need to swap the R and B channels since both OpenCV and Caffe use RGB format."
},
{
"code": null,
"e": 4586,
"s": 4578,
"text": "Python3"
},
{
"code": "# Read imageframe = cv2.imread(\"single.jpg\") # Specify the input image dimensionsinWidth = 368inHeight = 368 # Prepare the frame to be fed to the networkinpBlob = cv2.dnn.blobFromImage( frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) # Set the prepared object as the input blob of the networknet.setInput(inpBlob)",
"e": 4934,
"s": 4586,
"text": null
},
{
"code": null,
"e": 4942,
"s": 4934,
"text": "Python3"
},
{
"code": "output = net.forward()",
"e": 4965,
"s": 4942,
"text": null
},
{
"code": null,
"e": 4993,
"s": 4965,
"text": "The output is a 4D matrix :"
},
{
"code": null,
"e": 5565,
"s": 4993,
"text": "The first dimension being the image ID ()in case you pass more than one image to the network).The second dimension indicates the index of a key point. The model produces Confidence Maps and Part Affinity maps which are all concatenated. For COCO model it consists of 57 parts — 18 key point confidence Maps + 1 background + 19*2 Part Affinity Maps. Similarly, for MPII, it produces 44 points. We will be using only the first few points which correspond to Key points.The third dimension is the height of the output map.The fourth dimension is the width of the output map."
},
{
"code": null,
"e": 5660,
"s": 5565,
"text": "The first dimension being the image ID ()in case you pass more than one image to the network)."
},
{
"code": null,
"e": 6034,
"s": 5660,
"text": "The second dimension indicates the index of a key point. The model produces Confidence Maps and Part Affinity maps which are all concatenated. For COCO model it consists of 57 parts — 18 key point confidence Maps + 1 background + 19*2 Part Affinity Maps. Similarly, for MPII, it produces 44 points. We will be using only the first few points which correspond to Key points."
},
{
"code": null,
"e": 6087,
"s": 6034,
"text": "The third dimension is the height of the output map."
},
{
"code": null,
"e": 6140,
"s": 6087,
"text": "The fourth dimension is the width of the output map."
},
{
"code": null,
"e": 6206,
"s": 6140,
"text": "Once the key points are detected, we just plot them on the image."
},
{
"code": null,
"e": 6214,
"s": 6206,
"text": "Python3"
},
{
"code": "H = out.shape[2]W = out.shape[3]# Empty list to store the detected keypointspoints = []for i in range(len()): # confidence map of corresponding body's part. probMap = output[0, i, :, :] # Find global maxima of the probMap. minVal, prob, minLoc, point = cv2.minMaxLoc(probMap) # Scale the point to fit on the original image x = (frameWidth * point[0]) / W y = (frameHeight * point[1]) / H if prob > threshold: cv2.circle(frame, (int(x), int(y)), 15, (0, 255, 255), thickness=-1, lineType=cv.FILLED) cv2.putText(frame, \"{}\".format(i), (int(x), int( y)), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, lineType=cv2.LINE_AA) # Add the point to the list if the probability is greater than the threshold points.append((int(x), int(y))) else: points.append(None) cv2.imshow(\"Output-Keypoints\", frame)cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 7145,
"s": 6214,
"text": null
},
{
"code": null,
"e": 7253,
"s": 7145,
"text": "Fig(a) shows the key points plotted using COCO model. Fig(b) shows the key points plotted using MPII model."
},
{
"code": null,
"e": 7320,
"s": 7253,
"text": "This figure shows the skeleton formed by all the key points joined"
},
{
"code": null,
"e": 7328,
"s": 7320,
"text": "Python3"
},
{
"code": "for pair in POSE_PAIRS: partA = pair[0] partB = pair[1] if points[partA] and points[partB]: cv2.line(frameCopy, points[partA], points[partB], (0, 255, 0), 3)",
"e": 7504,
"s": 7328,
"text": null
},
{
"code": null,
"e": 7570,
"s": 7504,
"text": "We found that COCO model is 1.5 times slower than the MPI model. "
},
{
"code": null,
"e": 7610,
"s": 7570,
"text": "Sign languages to help disabled people."
},
{
"code": null,
"e": 7625,
"s": 7610,
"text": "Human tracking"
},
{
"code": null,
"e": 7632,
"s": 7625,
"text": "Gaming"
},
{
"code": null,
"e": 7651,
"s": 7632,
"text": "Video surveillance"
},
{
"code": null,
"e": 7693,
"s": 7651,
"text": "Advanced Driver Assistance Systems (ADAS)"
},
{
"code": null,
"e": 7712,
"s": 7693,
"text": "Action recognition"
},
{
"code": null,
"e": 7771,
"s": 7712,
"text": "https://github.com/CMU-Perceptual-Computing-Lab/openpose "
},
{
"code": null,
"e": 7866,
"s": 7771,
"text": "https://learnopencv.com/deep-learning-based-human-pose-estimation-using-opencv-cpp-python/ "
},
{
"code": null,
"e": 7911,
"s": 7866,
"text": "https://ieeexplore.ieee.org/document/9144178"
},
{
"code": null,
"e": 7925,
"s": 7911,
"text": "Deep-Learning"
},
{
"code": null,
"e": 7932,
"s": 7925,
"text": "OpenCV"
},
{
"code": null,
"e": 7939,
"s": 7932,
"text": "Picked"
},
{
"code": null,
"e": 7956,
"s": 7939,
"text": "Machine Learning"
},
{
"code": null,
"e": 7964,
"s": 7956,
"text": "Project"
},
{
"code": null,
"e": 7971,
"s": 7964,
"text": "Python"
},
{
"code": null,
"e": 7988,
"s": 7971,
"text": "Machine Learning"
}
]
|
What is currying function in JavaScript ? | 29 Sep, 2021
It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence. The translation of function happens something like this,
function simpleFunction(param1, param2, param3, .....) => function curriedFunction(param1)(param2)(param3)(....
We simply wrap function inside a function, which means we are going to return a function from another function to obtain this kind of translation. The parent function takes the first provided argument and returns the function that takes the next argument and this keeps on repeating till the number of arguments ends. Hopefully, the function that receives the last argument returns the expected result.
Note: An American mathematician named Haskell Curry developed this technique, that’s why it is called as currying.
Example 1: Let’s say we have the length, breadth, and height of a cuboid and we want to construct a function that can calculate the volume. The function is being called which consequently executes its code by provided arguments and returns the appropriate result, FInally console.log prints the returned value on console.
JavaScript
<script> function calculateVolume(length, breadth, height) { return length * breadth * height; } console.log(calculateVolume(4, 5, 6));</script>
Output:
120
Example 2: This example explains the currying technique with the help of closures. During the thread of execution, the calculateVolume() function will be invoked. Inside there is an anonymous function, receiving a parameter and returning some code. We are exposing our function from another function, so the closure will be created. Closure always contains the function definition along with the lexical environment of the parent, both things remain connected as a bundle. Hence, it does not matter where we invoke them, the all inner functions will always hold access to the variable of their parent.As soon as we have got the returned result as a function the next argument is ready to be passed, this process will continue till the second last function. Finally, the innermost return keyword returns the expected result.
JavaScript
<script> function calculateVolume(length) { return function (breadth) { return function (height) { return length * breadth * height; } } } console.log(calculateVolume(4)(5)(6));</script>
Output:
120
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence. The translation of function happens something like this,"
},
{
"code": null,
"e": 378,
"s": 266,
"text": "function simpleFunction(param1, param2, param3, .....) => function curriedFunction(param1)(param2)(param3)(...."
},
{
"code": null,
"e": 783,
"s": 378,
"text": "We simply wrap function inside a function, which means we are going to return a function from another function to obtain this kind of translation. The parent function takes the first provided argument and returns the function that takes the next argument and this keeps on repeating till the number of arguments ends. Hopefully, the function that receives the last argument returns the expected result. "
},
{
"code": null,
"e": 898,
"s": 783,
"text": "Note: An American mathematician named Haskell Curry developed this technique, that’s why it is called as currying."
},
{
"code": null,
"e": 1220,
"s": 898,
"text": "Example 1: Let’s say we have the length, breadth, and height of a cuboid and we want to construct a function that can calculate the volume. The function is being called which consequently executes its code by provided arguments and returns the appropriate result, FInally console.log prints the returned value on console."
},
{
"code": null,
"e": 1231,
"s": 1220,
"text": "JavaScript"
},
{
"code": "<script> function calculateVolume(length, breadth, height) { return length * breadth * height; } console.log(calculateVolume(4, 5, 6));</script>",
"e": 1392,
"s": 1231,
"text": null
},
{
"code": null,
"e": 1400,
"s": 1392,
"text": "Output:"
},
{
"code": null,
"e": 1404,
"s": 1400,
"text": "120"
},
{
"code": null,
"e": 2228,
"s": 1404,
"text": "Example 2: This example explains the currying technique with the help of closures. During the thread of execution, the calculateVolume() function will be invoked. Inside there is an anonymous function, receiving a parameter and returning some code. We are exposing our function from another function, so the closure will be created. Closure always contains the function definition along with the lexical environment of the parent, both things remain connected as a bundle. Hence, it does not matter where we invoke them, the all inner functions will always hold access to the variable of their parent.As soon as we have got the returned result as a function the next argument is ready to be passed, this process will continue till the second last function. Finally, the innermost return keyword returns the expected result."
},
{
"code": null,
"e": 2239,
"s": 2228,
"text": "JavaScript"
},
{
"code": "<script> function calculateVolume(length) { return function (breadth) { return function (height) { return length * breadth * height; } } } console.log(calculateVolume(4)(5)(6));</script>",
"e": 2486,
"s": 2239,
"text": null
},
{
"code": null,
"e": 2494,
"s": 2486,
"text": "Output:"
},
{
"code": null,
"e": 2498,
"s": 2494,
"text": "120"
},
{
"code": null,
"e": 2519,
"s": 2498,
"text": "javascript-functions"
},
{
"code": null,
"e": 2540,
"s": 2519,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2547,
"s": 2540,
"text": "Picked"
},
{
"code": null,
"e": 2558,
"s": 2547,
"text": "JavaScript"
},
{
"code": null,
"e": 2575,
"s": 2558,
"text": "Web Technologies"
},
{
"code": null,
"e": 2673,
"s": 2575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2734,
"s": 2673,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2774,
"s": 2734,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2815,
"s": 2774,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2857,
"s": 2815,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2879,
"s": 2857,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2912,
"s": 2879,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2974,
"s": 2912,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3035,
"s": 2974,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3085,
"s": 3035,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
sqrt() function for complex number in C++ | 30 Oct, 2020
The complex version of sqrt() function is defined in the complex header file. This function is used to calculate the square root of the complex number z with a branch cut along the negative real axis.
Syntax:
template <class T> complex<T>
sqrt(const complex<T>& z);
Parameters: This method takes a mandatory parameter z which represents the complex number whose square root is to be calculated.Return Value: This function returns the square root of the complex number z.
Below program illustrate the sqrt() function for complex number in C++:
cpp
// C++ program to demonstrate// example of sqrt() function. #include <math.h>#include <iostream>#include <complex>using namespace std; int main(){ cout << "Square root of -9 is "; cout << sqrt(complex<double>(-9.0, 0.0)) << endl; cout << "Square root of (-9, -0) is "; cout << sqrt(complex<double>(-9.0, -0.0)) << endl; return 0;}
Square root of -9 is (0,3)
Square root of (-9, -0) is (0,-3)
tobiasgrothmann
CPP-Functions
cpp-template
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Oct, 2020"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The complex version of sqrt() function is defined in the complex header file. This function is used to calculate the square root of the complex number z with a branch cut along the negative real axis."
},
{
"code": null,
"e": 239,
"s": 229,
"text": "Syntax: "
},
{
"code": null,
"e": 302,
"s": 239,
"text": "template <class T> complex<T>\n sqrt(const complex<T>& z);\n\n"
},
{
"code": null,
"e": 507,
"s": 302,
"text": "Parameters: This method takes a mandatory parameter z which represents the complex number whose square root is to be calculated.Return Value: This function returns the square root of the complex number z."
},
{
"code": null,
"e": 579,
"s": 507,
"text": "Below program illustrate the sqrt() function for complex number in C++:"
},
{
"code": null,
"e": 583,
"s": 579,
"text": "cpp"
},
{
"code": "// C++ program to demonstrate// example of sqrt() function. #include <math.h>#include <iostream>#include <complex>using namespace std; int main(){ cout << \"Square root of -9 is \"; cout << sqrt(complex<double>(-9.0, 0.0)) << endl; cout << \"Square root of (-9, -0) is \"; cout << sqrt(complex<double>(-9.0, -0.0)) << endl; return 0;}",
"e": 931,
"s": 583,
"text": null
},
{
"code": null,
"e": 993,
"s": 931,
"text": "Square root of -9 is (0,3)\nSquare root of (-9, -0) is (0,-3)\n"
},
{
"code": null,
"e": 1009,
"s": 993,
"text": "tobiasgrothmann"
},
{
"code": null,
"e": 1023,
"s": 1009,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1036,
"s": 1023,
"text": "cpp-template"
},
{
"code": null,
"e": 1040,
"s": 1036,
"text": "C++"
},
{
"code": null,
"e": 1053,
"s": 1040,
"text": "C++ Programs"
},
{
"code": null,
"e": 1057,
"s": 1053,
"text": "CPP"
},
{
"code": null,
"e": 1155,
"s": 1057,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1182,
"s": 1155,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1225,
"s": 1182,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1259,
"s": 1225,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1284,
"s": 1259,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 1303,
"s": 1284,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 1338,
"s": 1303,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 1372,
"s": 1338,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 1416,
"s": 1372,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 1475,
"s": 1416,
"text": "How to return multiple values from a function in C or C++?"
}
]
|
ML | OPTICS Clustering Explanation | 14 Jul, 2019
Prerequisites: DBSCAN Clustering
OPTICS Clustering stands for Ordering Points To Identify Cluster Structure. It draws inspiration from the DBSCAN clustering algorithm. It adds two more terms to the concepts of DBSCAN clustering. They are:-
Core Distance: It is the minimum value of radius required to classify a given point as a core point. If the given point is not a Core point, then it’s Core Distance is undefined.Reachability Distance: It is defined with respect to another data point q(Let). The Reachability distance between a point p and q is the maximum of the Core Distance of p and the Euclidean Distance(or some other distance metric) between p and q. Note that The Reachability Distance is not defined if q is not a Core point.
Core Distance: It is the minimum value of radius required to classify a given point as a core point. If the given point is not a Core point, then it’s Core Distance is undefined.
Reachability Distance: It is defined with respect to another data point q(Let). The Reachability distance between a point p and q is the maximum of the Core Distance of p and the Euclidean Distance(or some other distance metric) between p and q. Note that The Reachability Distance is not defined if q is not a Core point.
This clustering technique is different from other clustering techniques in the sense that this technique does not explicitly segment the data into clusters. Instead, it produces a visualization of Reachability distances and uses this visualization to cluster the data.
Pseudocode:
The following Pseudocode has been referred from the Wikipedia page of the algorithm.
OPTICS(DB, eps, MinPts)
#Repeating the process for all points in the database
for each point pt of DB
#Initializing the reachability distance of the selected point
pt.reachable_dist = UNDEFINED
for each unprocessed point pt of DB
#Getting the neighbours of the selected point
#according to the definitions of epsilon and
#minPts in DBSCAN
Nbrs = getNbrs(pt, eps)
mark pt as processed
output pt to the ordered list
#Checking if the selected point is not noise
if (core_dist(pt, eps, Minpts) != UNDEFINED)
#Initializing a priority queue to get the closest data point
#in terms of Reachability distance
Seeds = empty priority queue
#Calling the update function
update(Nbrs, pt, Seeds, eps, Minpts)
#Repeating the process for the next closest point
for each next q in Seeds
Nbrs' = getNbrs(q, eps)
mark q as processed
output q to the ordered list
if (core_dist(q, eps, Minpts) != UNDEFINED)
update(Nbrs', q, Seeds, eps, Minpts)
The pseudo-code for the update function is given below:
update(Nbrs, pt, Seeds, eps, MinPts)
#Calculating the core distance for the given point
coredist = core_dist(pt, eps, MinPts)
#Updating the Reachability distance for each neighbour of p
for each obj in Nbrs
if (obj is not processed)
new_reach_distance = max(coredist, dist(pt, obj))
#Checking if the neighbour point is in seeds
if (obj.reachable_dist == UNDEFINED)
#Updation step
obj.reachabled_dist = new_reach_distance
Seeds.insert(obj, new_reach_distance)
else
if (new_reach_distance < obj.reachable_dist)
#Updation step
o.reachable_dist = new_reach_distance
Seeds.move-up(obj, new_reach_distance)
OPTICS Clustering v/s DBSCAN Clustering:
Memory Cost : The OPTICS clustering technique requires more memory as it maintains a priority queue (Min Heap) to determine the next data point which is closest to the point currently being processed in terms of Reachability Distance. It also requires more computational power because the nearest neighbour queries are more complicated than radius queries in DBSCAN.Fewer Parameters : The OPTICS clustering technique does not need to maintain the epsilon parameter and is only given in the above pseudo-code to reduce the time taken. This leads to the reduction of the analytical process of parameter tuning.This technique does not segregate the given data into clusters. It merely produces a Reachability distance plot and it is upon the interpretation of the programmer to cluster the points accordingly.
Memory Cost : The OPTICS clustering technique requires more memory as it maintains a priority queue (Min Heap) to determine the next data point which is closest to the point currently being processed in terms of Reachability Distance. It also requires more computational power because the nearest neighbour queries are more complicated than radius queries in DBSCAN.
Fewer Parameters : The OPTICS clustering technique does not need to maintain the epsilon parameter and is only given in the above pseudo-code to reduce the time taken. This leads to the reduction of the analytical process of parameter tuning.
This technique does not segregate the given data into clusters. It merely produces a Reachability distance plot and it is upon the interpretation of the programmer to cluster the points accordingly.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 85,
"s": 52,
"text": "Prerequisites: DBSCAN Clustering"
},
{
"code": null,
"e": 292,
"s": 85,
"text": "OPTICS Clustering stands for Ordering Points To Identify Cluster Structure. It draws inspiration from the DBSCAN clustering algorithm. It adds two more terms to the concepts of DBSCAN clustering. They are:-"
},
{
"code": null,
"e": 793,
"s": 292,
"text": "Core Distance: It is the minimum value of radius required to classify a given point as a core point. If the given point is not a Core point, then it’s Core Distance is undefined.Reachability Distance: It is defined with respect to another data point q(Let). The Reachability distance between a point p and q is the maximum of the Core Distance of p and the Euclidean Distance(or some other distance metric) between p and q. Note that The Reachability Distance is not defined if q is not a Core point."
},
{
"code": null,
"e": 972,
"s": 793,
"text": "Core Distance: It is the minimum value of radius required to classify a given point as a core point. If the given point is not a Core point, then it’s Core Distance is undefined."
},
{
"code": null,
"e": 1295,
"s": 972,
"text": "Reachability Distance: It is defined with respect to another data point q(Let). The Reachability distance between a point p and q is the maximum of the Core Distance of p and the Euclidean Distance(or some other distance metric) between p and q. Note that The Reachability Distance is not defined if q is not a Core point."
},
{
"code": null,
"e": 1564,
"s": 1295,
"text": "This clustering technique is different from other clustering techniques in the sense that this technique does not explicitly segment the data into clusters. Instead, it produces a visualization of Reachability distances and uses this visualization to cluster the data."
},
{
"code": null,
"e": 1576,
"s": 1564,
"text": "Pseudocode:"
},
{
"code": null,
"e": 1661,
"s": 1576,
"text": "The following Pseudocode has been referred from the Wikipedia page of the algorithm."
},
{
"code": null,
"e": 2814,
"s": 1661,
"text": "OPTICS(DB, eps, MinPts)\n\n #Repeating the process for all points in the database\n for each point pt of DB\n\n #Initializing the reachability distance of the selected point\n pt.reachable_dist = UNDEFINED\n for each unprocessed point pt of DB\n\n #Getting the neighbours of the selected point\n #according to the definitions of epsilon and\n #minPts in DBSCAN\n Nbrs = getNbrs(pt, eps)\n\n mark pt as processed\n output pt to the ordered list\n\n #Checking if the selected point is not noise\n if (core_dist(pt, eps, Minpts) != UNDEFINED)\n\n #Initializing a priority queue to get the closest data point\n #in terms of Reachability distance\n Seeds = empty priority queue\n\n #Calling the update function\n update(Nbrs, pt, Seeds, eps, Minpts)\n\n #Repeating the process for the next closest point\n for each next q in Seeds\n Nbrs' = getNbrs(q, eps)\n mark q as processed\n output q to the ordered list\n if (core_dist(q, eps, Minpts) != UNDEFINED)\n update(Nbrs', q, Seeds, eps, Minpts)\n"
},
{
"code": null,
"e": 2870,
"s": 2814,
"text": "The pseudo-code for the update function is given below:"
},
{
"code": null,
"e": 3662,
"s": 2870,
"text": "update(Nbrs, pt, Seeds, eps, MinPts)\n\n #Calculating the core distance for the given point\n coredist = core_dist(pt, eps, MinPts)\n\n #Updating the Reachability distance for each neighbour of p\n for each obj in Nbrs\n if (obj is not processed)\n new_reach_distance = max(coredist, dist(pt, obj))\n\n #Checking if the neighbour point is in seeds\n if (obj.reachable_dist == UNDEFINED)\n\n #Updation step\n obj.reachabled_dist = new_reach_distance\n Seeds.insert(obj, new_reach_distance)\n else \n if (new_reach_distance < obj.reachable_dist)\n\n #Updation step\n o.reachable_dist = new_reach_distance\n Seeds.move-up(obj, new_reach_distance)\n"
},
{
"code": null,
"e": 3703,
"s": 3662,
"text": "OPTICS Clustering v/s DBSCAN Clustering:"
},
{
"code": null,
"e": 4510,
"s": 3703,
"text": "Memory Cost : The OPTICS clustering technique requires more memory as it maintains a priority queue (Min Heap) to determine the next data point which is closest to the point currently being processed in terms of Reachability Distance. It also requires more computational power because the nearest neighbour queries are more complicated than radius queries in DBSCAN.Fewer Parameters : The OPTICS clustering technique does not need to maintain the epsilon parameter and is only given in the above pseudo-code to reduce the time taken. This leads to the reduction of the analytical process of parameter tuning.This technique does not segregate the given data into clusters. It merely produces a Reachability distance plot and it is upon the interpretation of the programmer to cluster the points accordingly."
},
{
"code": null,
"e": 4877,
"s": 4510,
"text": "Memory Cost : The OPTICS clustering technique requires more memory as it maintains a priority queue (Min Heap) to determine the next data point which is closest to the point currently being processed in terms of Reachability Distance. It also requires more computational power because the nearest neighbour queries are more complicated than radius queries in DBSCAN."
},
{
"code": null,
"e": 5120,
"s": 4877,
"text": "Fewer Parameters : The OPTICS clustering technique does not need to maintain the epsilon parameter and is only given in the above pseudo-code to reduce the time taken. This leads to the reduction of the analytical process of parameter tuning."
},
{
"code": null,
"e": 5319,
"s": 5120,
"text": "This technique does not segregate the given data into clusters. It merely produces a Reachability distance plot and it is upon the interpretation of the programmer to cluster the points accordingly."
},
{
"code": null,
"e": 5336,
"s": 5319,
"text": "Machine Learning"
},
{
"code": null,
"e": 5343,
"s": 5336,
"text": "Python"
},
{
"code": null,
"e": 5360,
"s": 5343,
"text": "Machine Learning"
}
]
|
Writing to Excel Sheet Using EPPlus in C# | 14 Feb, 2020
EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc.
First of all install EPPlus using Packet Manager console by writing the following command:
Install-Package EPPlus
Let’s see how to create and write to an excel-sheet using C#.
using System;using System.IO;// The following to two namespace contains// the functions for manipulating the// Excel file using OfficeOpenXml;using OfficeOpenXml.Style; class Program{ static void Main(string[] args) { var Articles = new[] { new { Id = "101", Name = "C++" }, new { Id = "102", Name = "Python" }, new { Id = "103", Name = "Java Script" }, new { Id = "104", Name = "GO" }, new { Id = "105", Name = "Java" }, new { Id = "106", Name = "C#" } }; // Creating an instance // of ExcelPackage ExcelPackage excel = new ExcelPackage(); // name of the sheet var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); // setting the properties // of the work sheet workSheet.TabColor = System.Drawing.Color.Black; workSheet.DefaultRowHeight = 12; // Setting the properties // of the first row workSheet.Row(1).Height = 20; workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; workSheet.Row(1).Style.Font.Bold = true; // Header of the Excel sheet workSheet.Cells[1, 1].Value = "S.No"; workSheet.Cells[1, 2].Value = "Id"; workSheet.Cells[1, 3].Value = "Name"; // Inserting the article data into excel // sheet by using the for each loop // As we have values to the first row // we will start with second row int recordIndex = 2; foreach (var article in Articles) { workSheet.Cells[recordIndex, 1].Value = (recordIndex - 1).ToString(); workSheet.Cells[recordIndex, 2].Value = article.Id; workSheet.Cells[recordIndex, 3].Value = article.Name; recordIndex++; } // By default, the column width is not // set to auto fit for the content // of the range, so we are using // AutoFit() method here. workSheet.Column(1).AutoFit(); workSheet.Column(2).AutoFit(); workSheet.Column(3).AutoFit(); // file name with .xlsx extension string p_strPath = "H:\\geeksforgeeks.xlsx"; if (File.Exists(p_strPath)) File.Delete(p_strPath); // Create excel file on physical disk FileStream objFileStrm = File.Create(p_strPath); objFileStrm.Close(); // Write content to excel file File.WriteAllBytes(p_strPath, excel.GetAsByteArray()); //Close Excel package excel.Dispose(); Console.ReadKey(); }}
Output:
In this program, we are taking static values for the Articles data but in real-time, we can use database call and foreach loop for iteration of each record.
vibs2006
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc."
},
{
"code": null,
"e": 430,
"s": 339,
"text": "First of all install EPPlus using Packet Manager console by writing the following command:"
},
{
"code": null,
"e": 455,
"s": 430,
"text": "Install-Package EPPlus \n"
},
{
"code": null,
"e": 517,
"s": 455,
"text": "Let’s see how to create and write to an excel-sheet using C#."
},
{
"code": "using System;using System.IO;// The following to two namespace contains// the functions for manipulating the// Excel file using OfficeOpenXml;using OfficeOpenXml.Style; class Program{ static void Main(string[] args) { var Articles = new[] { new { Id = \"101\", Name = \"C++\" }, new { Id = \"102\", Name = \"Python\" }, new { Id = \"103\", Name = \"Java Script\" }, new { Id = \"104\", Name = \"GO\" }, new { Id = \"105\", Name = \"Java\" }, new { Id = \"106\", Name = \"C#\" } }; // Creating an instance // of ExcelPackage ExcelPackage excel = new ExcelPackage(); // name of the sheet var workSheet = excel.Workbook.Worksheets.Add(\"Sheet1\"); // setting the properties // of the work sheet workSheet.TabColor = System.Drawing.Color.Black; workSheet.DefaultRowHeight = 12; // Setting the properties // of the first row workSheet.Row(1).Height = 20; workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; workSheet.Row(1).Style.Font.Bold = true; // Header of the Excel sheet workSheet.Cells[1, 1].Value = \"S.No\"; workSheet.Cells[1, 2].Value = \"Id\"; workSheet.Cells[1, 3].Value = \"Name\"; // Inserting the article data into excel // sheet by using the for each loop // As we have values to the first row // we will start with second row int recordIndex = 2; foreach (var article in Articles) { workSheet.Cells[recordIndex, 1].Value = (recordIndex - 1).ToString(); workSheet.Cells[recordIndex, 2].Value = article.Id; workSheet.Cells[recordIndex, 3].Value = article.Name; recordIndex++; } // By default, the column width is not // set to auto fit for the content // of the range, so we are using // AutoFit() method here. workSheet.Column(1).AutoFit(); workSheet.Column(2).AutoFit(); workSheet.Column(3).AutoFit(); // file name with .xlsx extension string p_strPath = \"H:\\\\geeksforgeeks.xlsx\"; if (File.Exists(p_strPath)) File.Delete(p_strPath); // Create excel file on physical disk FileStream objFileStrm = File.Create(p_strPath); objFileStrm.Close(); // Write content to excel file File.WriteAllBytes(p_strPath, excel.GetAsByteArray()); //Close Excel package excel.Dispose(); Console.ReadKey(); }}",
"e": 3372,
"s": 517,
"text": null
},
{
"code": null,
"e": 3380,
"s": 3372,
"text": "Output:"
},
{
"code": null,
"e": 3537,
"s": 3380,
"text": "In this program, we are taking static values for the Articles data but in real-time, we can use database call and foreach loop for iteration of each record."
},
{
"code": null,
"e": 3546,
"s": 3537,
"text": "vibs2006"
},
{
"code": null,
"e": 3549,
"s": 3546,
"text": "C#"
}
]
|
Test Bed | The test execution environment configured for testing. Test bed consists of specific hardware, software, Operating system, network configuration, the product under test, other system software and application software.
It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test.
A typical test bed for a web-based application is given below:
Web Server - IIS/Apache
Database - MS SQL
OS - Windows/ Linux
Browser - IE/FireFox
Java version : version 6 | [
{
"code": null,
"e": 6097,
"s": 5879,
"text": "The test execution environment configured for testing. Test bed consists of specific hardware, software, Operating system, network configuration, the product under test, other system software and application software."
},
{
"code": null,
"e": 6334,
"s": 6097,
"text": "It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test."
},
{
"code": null,
"e": 6397,
"s": 6334,
"text": "A typical test bed for a web-based application is given below:"
}
]
|
DBMS - Data Recovery | DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data.
To see where the problem has occurred, we generalize a failure into various categories, as follows −
A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt.
Reasons for a transaction failure could be −
Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.
Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition.
System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.
System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction.
There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure.
Examples may include operating system errors.
In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently.
Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage.
We have already described the storage system. In brief, the storage structure can be divided into two categories −
Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.
Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information.
Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.
Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM.
When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none.
When a DBMS recovers from a crash, it should maintain the following −
It should check the states of all the transactions, which were being executed.
It should check the states of all the transactions, which were being executed.
A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.
A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case.
It should check whether the transaction can be completed now or it needs to be rolled back.
It should check whether the transaction can be completed now or it needs to be rolled back.
No transactions would be allowed to leave the DBMS in an inconsistent state.
No transactions would be allowed to leave the DBMS in an inconsistent state.
There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −
Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.
Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database.
Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.
Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated.
Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe.
Log-based recovery works as follows −
The log file is kept on a stable storage media.
The log file is kept on a stable storage media.
When a transaction enters the system and starts execution, it writes a log about it.
When a transaction enters the system and starts execution, it writes a log about it.
<Tn, Start>
When the transaction modifies an item X, it write logs as follows −
When the transaction modifies an item X, it write logs as follows −
<Tn, X, V1, V2>
It reads Tn has changed the value of X, from V1 to V2.
When the transaction finishes, it logs −
<Tn, commit>
The database can be modified using two approaches −
Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.
Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits.
Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.
Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation.
When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'.
Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.
When a system with concurrent transactions crashes and recovers, it behaves in the following manner −
The recovery system reads the logs backwards from the end to the last checkpoint.
The recovery system reads the logs backwards from the end to the last checkpoint.
It maintains two lists, an undo-list and a redo-list.
It maintains two lists, an undo-list and a redo-list.
If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list.
If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list.
If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list.
If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list.
All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs. | [
{
"code": null,
"e": 2777,
"s": 2416,
"text": "DBMS is a highly complex system with hundreds of transactions being executed every second. The durability and robustness of a DBMS depends on its complex architecture and its underlying hardware and system software. If it fails or crashes amid transactions, it is expected that the system would follow some sort of algorithm or techniques to recover lost data."
},
{
"code": null,
"e": 2878,
"s": 2777,
"text": "To see where the problem has occurred, we generalize a failure into various categories, as follows −"
},
{
"code": null,
"e": 3081,
"s": 2878,
"text": "A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any further. This is called transaction failure where only a few transactions or processes are hurt."
},
{
"code": null,
"e": 3126,
"s": 3081,
"text": "Reasons for a transaction failure could be −"
},
{
"code": null,
"e": 3243,
"s": 3126,
"text": "Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."
},
{
"code": null,
"e": 3360,
"s": 3243,
"text": "Logical errors − Where a transaction cannot complete because it has some code error or any internal error condition."
},
{
"code": null,
"e": 3640,
"s": 3360,
"text": "System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."
},
{
"code": null,
"e": 3920,
"s": 3640,
"text": "System errors − Where the database system itself terminates an active transaction because the DBMS is not able to execute it, or it has to stop because of some system condition. For example, in case of deadlock or resource unavailability, the system aborts an active transaction."
},
{
"code": null,
"e": 4149,
"s": 3920,
"text": "There are problems − external to the system − that may cause the system to stop abruptly and cause the system to crash. For example, interruptions in power supply may cause the failure of underlying hardware or software failure."
},
{
"code": null,
"e": 4195,
"s": 4149,
"text": "Examples may include operating system errors."
},
{
"code": null,
"e": 4324,
"s": 4195,
"text": "In early days of technology evolution, it was a common problem where hard-disk drives or storage drives used to fail frequently."
},
{
"code": null,
"e": 4484,
"s": 4324,
"text": "Disk failures include formation of bad sectors, unreachability to the disk, disk head crash or any other failure, which destroys all or a part of disk storage."
},
{
"code": null,
"e": 4599,
"s": 4484,
"text": "We have already described the storage system. In brief, the storage structure can be divided into two categories −"
},
{
"code": null,
"e": 4941,
"s": 4599,
"text": "Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."
},
{
"code": null,
"e": 5283,
"s": 4941,
"text": "Volatile storage − As the name suggests, a volatile storage cannot survive system crashes. Volatile storage devices are placed very close to the CPU; normally they are embedded onto the chipset itself. For example, main memory and cache memory are examples of volatile storage. They are fast but can store only a small amount of information."
},
{
"code": null,
"e": 5531,
"s": 5283,
"text": "Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."
},
{
"code": null,
"e": 5779,
"s": 5531,
"text": "Non-volatile storage − These memories are made to survive system crashes. They are huge in data storage capacity, but slower in accessibility. Examples may include hard-disks, magnetic tapes, flash memory, and non-volatile (battery backed up) RAM."
},
{
"code": null,
"e": 6139,
"s": 5779,
"text": "When a system crashes, it may have several transactions being executed and various files opened for them to modify the data items. Transactions are made of various operations, which are atomic in nature. But according to ACID properties of DBMS, atomicity of transactions as a whole must be maintained, that is, either all the operations are executed or none."
},
{
"code": null,
"e": 6209,
"s": 6139,
"text": "When a DBMS recovers from a crash, it should maintain the following −"
},
{
"code": null,
"e": 6288,
"s": 6209,
"text": "It should check the states of all the transactions, which were being executed."
},
{
"code": null,
"e": 6367,
"s": 6288,
"text": "It should check the states of all the transactions, which were being executed."
},
{
"code": null,
"e": 6489,
"s": 6367,
"text": "A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."
},
{
"code": null,
"e": 6611,
"s": 6489,
"text": "A transaction may be in the middle of some operation; the DBMS must ensure the atomicity of the transaction in this case."
},
{
"code": null,
"e": 6703,
"s": 6611,
"text": "It should check whether the transaction can be completed now or it needs to be rolled back."
},
{
"code": null,
"e": 6795,
"s": 6703,
"text": "It should check whether the transaction can be completed now or it needs to be rolled back."
},
{
"code": null,
"e": 6872,
"s": 6795,
"text": "No transactions would be allowed to leave the DBMS in an inconsistent state."
},
{
"code": null,
"e": 6949,
"s": 6872,
"text": "No transactions would be allowed to leave the DBMS in an inconsistent state."
},
{
"code": null,
"e": 7076,
"s": 6949,
"text": "There are two types of techniques, which can help a DBMS in recovering as well as maintaining the atomicity of a transaction −"
},
{
"code": null,
"e": 7200,
"s": 7076,
"text": "Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."
},
{
"code": null,
"e": 7324,
"s": 7200,
"text": "Maintaining the logs of each transaction, and writing them onto some stable storage before actually modifying the database."
},
{
"code": null,
"e": 7443,
"s": 7324,
"text": "Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."
},
{
"code": null,
"e": 7562,
"s": 7443,
"text": "Maintaining shadow paging, where the changes are done on a volatile memory, and later, the actual database is updated."
},
{
"code": null,
"e": 7791,
"s": 7562,
"text": "Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe."
},
{
"code": null,
"e": 7829,
"s": 7791,
"text": "Log-based recovery works as follows −"
},
{
"code": null,
"e": 7877,
"s": 7829,
"text": "The log file is kept on a stable storage media."
},
{
"code": null,
"e": 7925,
"s": 7877,
"text": "The log file is kept on a stable storage media."
},
{
"code": null,
"e": 8010,
"s": 7925,
"text": "When a transaction enters the system and starts execution, it writes a log about it."
},
{
"code": null,
"e": 8095,
"s": 8010,
"text": "When a transaction enters the system and starts execution, it writes a log about it."
},
{
"code": null,
"e": 8108,
"s": 8095,
"text": "<Tn, Start>\n"
},
{
"code": null,
"e": 8176,
"s": 8108,
"text": "When the transaction modifies an item X, it write logs as follows −"
},
{
"code": null,
"e": 8244,
"s": 8176,
"text": "When the transaction modifies an item X, it write logs as follows −"
},
{
"code": null,
"e": 8261,
"s": 8244,
"text": "<Tn, X, V1, V2>\n"
},
{
"code": null,
"e": 8316,
"s": 8261,
"text": "It reads Tn has changed the value of X, from V1 to V2."
},
{
"code": null,
"e": 8357,
"s": 8316,
"text": "When the transaction finishes, it logs −"
},
{
"code": null,
"e": 8371,
"s": 8357,
"text": "<Tn, commit>\n"
},
{
"code": null,
"e": 8423,
"s": 8371,
"text": "The database can be modified using two approaches −"
},
{
"code": null,
"e": 8558,
"s": 8423,
"text": "Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."
},
{
"code": null,
"e": 8693,
"s": 8558,
"text": "Deferred database modification − All logs are written on to the stable storage and the database is updated when a transaction commits."
},
{
"code": null,
"e": 8846,
"s": 8693,
"text": "Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."
},
{
"code": null,
"e": 8999,
"s": 8846,
"text": "Immediate database modification − Each log follows an actual database modification. That is, the database is modified immediately after every operation."
},
{
"code": null,
"e": 9283,
"s": 8999,
"text": "When more than one transaction are being executed in parallel, the logs are interleaved. At the time of recovery, it would become hard for the recovery system to backtrack all logs, and then start recovering. To ease this situation, most modern DBMS use the concept of 'checkpoints'."
},
{
"code": null,
"e": 9716,
"s": 9283,
"text": "Keeping and maintaining logs in real time and in real environment may fill out all the memory space available in the system. As time passes, the log file may grow too big to be handled at all. Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed."
},
{
"code": null,
"e": 9818,
"s": 9716,
"text": "When a system with concurrent transactions crashes and recovers, it behaves in the following manner −"
},
{
"code": null,
"e": 9900,
"s": 9818,
"text": "The recovery system reads the logs backwards from the end to the last checkpoint."
},
{
"code": null,
"e": 9982,
"s": 9900,
"text": "The recovery system reads the logs backwards from the end to the last checkpoint."
},
{
"code": null,
"e": 10036,
"s": 9982,
"text": "It maintains two lists, an undo-list and a redo-list."
},
{
"code": null,
"e": 10090,
"s": 10036,
"text": "It maintains two lists, an undo-list and a redo-list."
},
{
"code": null,
"e": 10222,
"s": 10090,
"text": "If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list."
},
{
"code": null,
"e": 10354,
"s": 10222,
"text": "If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just <Tn, Commit>, it puts the transaction in the redo-list."
},
{
"code": null,
"e": 10477,
"s": 10354,
"text": "If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list."
},
{
"code": null,
"e": 10600,
"s": 10477,
"text": "If the recovery system sees a log with <Tn, Start> but no commit or abort log found, it puts the transaction in undo-list."
}
]
|
JavaScript | Reflect.apply() Method | 29 Sep, 2021
The Reflect.apply() method is a standard build-in object in JavaScript which is used to call a function using the specified argument. It works similar to the Function.prototype.apply() method to call a function, but in a efficient manner and easy to understand.Syntax:
Reflect.apply(target, thisArgument, argumentsList)
Parameter: This method accepts three parameters as mentioned above and described below:
target: This parameter is the target function which is going to be called.
thisArgument: This parameter has the this value which is required for the calling the target function.
ArgumentsList: This parameter is an array-like object specifying the argument with which target should be called.
Return Value: Calling the given Target function resulted in the specified this value and arguments.Exceptions: A TypeError is exception given as the result, when the target is not callable.Below examples illustrate the Reflect.apply() Method in JavaScript:Example 1: List argument is passed and dictionary – object is created.
javascript
function geeks1 (a, b, c) { this.x = a; this.y = b; this.z = c; }const obj = {}; Reflect.apply ( geeks1 , obj, [12,42,32] ); console.log( obj );
Output:
{ x: 12, y: 42, z: 32 }
Example 2: In this example, the empty list argument is passed and the function is called. And the second portion contains mathematical computation, finding the minimum element from the list.
javascript
var geeks2 = function() { console.log(this); } Reflect.apply(geeks2, 'GeeksforGeeks', []); var list= [31, 45, 143, 5]; console.log(Reflect.apply(Math.min, undefined, list));
Output:
String { "GeeksforGeeks" }
5
Example 3:
javascript
// Converting the list of integer into char stringconsole.log(Reflect.apply(String.fromCharCode, undefined, [103, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115])) // Extract the indexed value of string(character)console.log(Reflect.apply(''.charAt, 'shubham', [3]))
Output:
geeksforgeeks
b
Supported Browsers: The browsers supported by JavaScript Reflect.apply() Method are listed below:
Google Chrome 49 and above
Edge 12 and above
Firefox 42 and above
Opera 36 and above
Safari 10 and above
Akanksha_Rai
ysachin2314
javascript-functions
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": "\n29 Sep, 2021"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "The Reflect.apply() method is a standard build-in object in JavaScript which is used to call a function using the specified argument. It works similar to the Function.prototype.apply() method to call a function, but in a efficient manner and easy to understand.Syntax: "
},
{
"code": null,
"e": 350,
"s": 299,
"text": "Reflect.apply(target, thisArgument, argumentsList)"
},
{
"code": null,
"e": 440,
"s": 350,
"text": "Parameter: This method accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 515,
"s": 440,
"text": "target: This parameter is the target function which is going to be called."
},
{
"code": null,
"e": 618,
"s": 515,
"text": "thisArgument: This parameter has the this value which is required for the calling the target function."
},
{
"code": null,
"e": 732,
"s": 618,
"text": "ArgumentsList: This parameter is an array-like object specifying the argument with which target should be called."
},
{
"code": null,
"e": 1061,
"s": 732,
"text": "Return Value: Calling the given Target function resulted in the specified this value and arguments.Exceptions: A TypeError is exception given as the result, when the target is not callable.Below examples illustrate the Reflect.apply() Method in JavaScript:Example 1: List argument is passed and dictionary – object is created. "
},
{
"code": null,
"e": 1072,
"s": 1061,
"text": "javascript"
},
{
"code": "function geeks1 (a, b, c) { this.x = a; this.y = b; this.z = c; }const obj = {}; Reflect.apply ( geeks1 , obj, [12,42,32] ); console.log( obj ); ",
"e": 1230,
"s": 1072,
"text": null
},
{
"code": null,
"e": 1240,
"s": 1230,
"text": "Output: "
},
{
"code": null,
"e": 1264,
"s": 1240,
"text": "{ x: 12, y: 42, z: 32 }"
},
{
"code": null,
"e": 1457,
"s": 1264,
"text": "Example 2: In this example, the empty list argument is passed and the function is called. And the second portion contains mathematical computation, finding the minimum element from the list. "
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": "javascript"
},
{
"code": "var geeks2 = function() { console.log(this); } Reflect.apply(geeks2, 'GeeksforGeeks', []); var list= [31, 45, 143, 5]; console.log(Reflect.apply(Math.min, undefined, list));",
"e": 1645,
"s": 1468,
"text": null
},
{
"code": null,
"e": 1655,
"s": 1645,
"text": "Output: "
},
{
"code": null,
"e": 1684,
"s": 1655,
"text": "String { \"GeeksforGeeks\" }\n5"
},
{
"code": null,
"e": 1697,
"s": 1684,
"text": "Example 3: "
},
{
"code": null,
"e": 1708,
"s": 1697,
"text": "javascript"
},
{
"code": "// Converting the list of integer into char stringconsole.log(Reflect.apply(String.fromCharCode, undefined, [103, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115])) // Extract the indexed value of string(character)console.log(Reflect.apply(''.charAt, 'shubham', [3]))",
"e": 2000,
"s": 1708,
"text": null
},
{
"code": null,
"e": 2010,
"s": 2000,
"text": "Output: "
},
{
"code": null,
"e": 2026,
"s": 2010,
"text": "geeksforgeeks\nb"
},
{
"code": null,
"e": 2126,
"s": 2026,
"text": "Supported Browsers: The browsers supported by JavaScript Reflect.apply() Method are listed below: "
},
{
"code": null,
"e": 2153,
"s": 2126,
"text": "Google Chrome 49 and above"
},
{
"code": null,
"e": 2171,
"s": 2153,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2192,
"s": 2171,
"text": "Firefox 42 and above"
},
{
"code": null,
"e": 2211,
"s": 2192,
"text": "Opera 36 and above"
},
{
"code": null,
"e": 2231,
"s": 2211,
"text": "Safari 10 and above"
},
{
"code": null,
"e": 2246,
"s": 2233,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2258,
"s": 2246,
"text": "ysachin2314"
},
{
"code": null,
"e": 2279,
"s": 2258,
"text": "javascript-functions"
},
{
"code": null,
"e": 2290,
"s": 2279,
"text": "JavaScript"
},
{
"code": null,
"e": 2307,
"s": 2290,
"text": "Web Technologies"
}
]
|
How I can replace a JavaScript alert pop up with a fancy alert box? | To design a custom JavaScript alert box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a fancy alert box different from the standard JavaScript alert box −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #91FF00;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id = "confirm">
<div class = "message">This is a warning message.</div>
<button class ="yes">OK</button>
</div>
<input type = "button" value = "Click Me" onclick = "functionAlert();" />
</body>
</html> | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "To design a custom JavaScript alert box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a fancy alert box different from the standard JavaScript alert box −"
},
{
"code": null,
"e": 1273,
"s": 1263,
"text": "Live Demo"
},
{
"code": null,
"e": 2791,
"s": 1273,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #91FF00;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 80px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id = \"confirm\">\n <div class = \"message\">This is a warning message.</div>\n <button class =\"yes\">OK</button>\n </div>\n <input type = \"button\" value = \"Click Me\" onclick = \"functionAlert();\" />\n </body>\n</html>"
}
]
|
Which is faster, a MySQL CASE statement or a PHP if statement? | The MySQL CASE statement is faster in comparison to PHP if statement. The PHP if statement takes too much time because it loads data and then process while CASE statement does not.
Let us first create a table and work around an example of MySQL CASE statement −
mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(500);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(1000);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 100 |
| 500 |
| 1000 |
+-------+
3 rows in set (0.00 sec)
Following is the query for MySQL CASE statement −
mysql> select Value, case when Value > 500 THEN "It is greater than or equal to 1000"
else
"It is lower than 1000"
end as comparison from DemoTable;
This will produce the following output −
+-------+-------------------------------------+
| Value | comparison |
+-------+-------------------------------------+
| 100 | It is lower than 1000 |
| 500 | It is lower than 1000 |
| 1000 | It is greater than or equal to 1000 |
+-------+-------------------------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "The MySQL CASE statement is faster in comparison to PHP if statement. The PHP if statement takes too much time because it loads data and then process while CASE statement does not."
},
{
"code": null,
"e": 1324,
"s": 1243,
"text": "Let us first create a table and work around an example of MySQL CASE statement −"
},
{
"code": null,
"e": 1404,
"s": 1324,
"text": "mysql> create table DemoTable (Value int);\nQuery OK, 0 rows affected (0.70 sec)"
},
{
"code": null,
"e": 1460,
"s": 1404,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1695,
"s": 1460,
"text": "mysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values(500);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(1000);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1755,
"s": 1695,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1786,
"s": 1755,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1827,
"s": 1786,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1922,
"s": 1827,
"text": "+-------+\n| Value |\n+-------+\n| 100 |\n| 500 |\n| 1000 |\n+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1972,
"s": 1922,
"text": "Following is the query for MySQL CASE statement −"
},
{
"code": null,
"e": 2130,
"s": 1972,
"text": "mysql> select Value, case when Value > 500 THEN \"It is greater than or equal to 1000\"\n else\n \"It is lower than 1000\"\n end as comparison from DemoTable;"
},
{
"code": null,
"e": 2171,
"s": 2130,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2532,
"s": 2171,
"text": "+-------+-------------------------------------+\n| Value | comparison |\n+-------+-------------------------------------+\n| 100 | It is lower than 1000 |\n| 500 | It is lower than 1000 |\n| 1000 | It is greater than or equal to 1000 |\n+-------+-------------------------------------+\n3 rows in set (0.00 sec)"
}
]
|
Explain Compile time and Run time initialization in C programming? | Let’s take the concept of arrays to about compile time and run time initialization −
Array is a collection of items stored at contiguous memory locations and elements can access by using indices.
In compile time initialization, user has to enter the details in the program itself.
Compile time initialization is same as variable initialization. The general form of initialization of array is as follows −
type name[size] = { list_of_values };
//integer array initialization
int rollnumbers[4]={ 2, 5, 6, 7};
//float array initialization
float area[5]={ 23.4, 6.8, 5.5,7.3,2.4 };
//character array initialization
char name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\0' };
Following is a C program to display array −
Live Demo
#include<stdio.h>
void main(){
//Declaring array with compile time initialization//
int array[5]={1,2,3,4,5};
//Declaring variables//
int i;
//Printing O/p using for loop//
printf("Displaying array of elements :");
for(i=0;i<5;i++){
printf("%d ",array[i]);
}
}
Displaying array of elements :1 2 3 4 5
Using runtime initialization user can get a chance of accepting or entering different values during different runs of program.
It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function.
Following is a C program to calculate sum and product of all elements in an array using run time compilation −
Live Demo
#include<stdio.h>
void main(){
//Declaring the array - run time//
int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
//Reading elements into the array's A and B using for loop//
printf("Enter elements into the array A: \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("A[%d][%d] :",i,j);
scanf("%d",&A[i][j]);
}
printf("\n");
}
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf("B[%d][%d] :",i,j);
scanf("%d",&B[i][j]);
}
printf("\n");
}
//Calculating sum and printing output//
printf("Sum array is : \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
sum[i][j]=A[i][j]+B[i][j];
printf("%d\t",sum[i][j]);
}
printf("\n");
}
//Calculating product and printing output//
printf("Product array is : \n");
for(i=0;i<2;i++){
for(j=0;j<3;j++){
product[i][j]=A[i][j]*B[i][j];
printf("%d\t",product[i][j]);
}
printf("\n");
}
}
Enter elements into the array A:
A[0][0] :A[0][1] :A[0][2] :
A[1][0] :A[1][1] :A[1][2] :
B[0][0] :B[0][1] :B[0][2] :
B[1][0] :B[1][1] :B[1][2] :
Sum array is :
000
000
Product array is :
000
000 | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Let’s take the concept of arrays to about compile time and run time initialization −"
},
{
"code": null,
"e": 1258,
"s": 1147,
"text": "Array is a collection of items stored at contiguous memory locations and elements can access by using indices."
},
{
"code": null,
"e": 1343,
"s": 1258,
"text": "In compile time initialization, user has to enter the details in the program itself."
},
{
"code": null,
"e": 1467,
"s": 1343,
"text": "Compile time initialization is same as variable initialization. The general form of initialization of array is as follows −"
},
{
"code": null,
"e": 1737,
"s": 1467,
"text": "type name[size] = { list_of_values };\n//integer array initialization\nint rollnumbers[4]={ 2, 5, 6, 7};\n//float array initialization\nfloat area[5]={ 23.4, 6.8, 5.5,7.3,2.4 };\n//character array initialization\nchar name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\\0' };"
},
{
"code": null,
"e": 1781,
"s": 1737,
"text": "Following is a C program to display array −"
},
{
"code": null,
"e": 1792,
"s": 1781,
"text": " Live Demo"
},
{
"code": null,
"e": 2083,
"s": 1792,
"text": "#include<stdio.h>\nvoid main(){\n //Declaring array with compile time initialization//\n int array[5]={1,2,3,4,5};\n //Declaring variables//\n int i;\n //Printing O/p using for loop//\n printf(\"Displaying array of elements :\");\n for(i=0;i<5;i++){\n printf(\"%d \",array[i]);\n }\n}"
},
{
"code": null,
"e": 2123,
"s": 2083,
"text": "Displaying array of elements :1 2 3 4 5"
},
{
"code": null,
"e": 2250,
"s": 2123,
"text": "Using runtime initialization user can get a chance of accepting or entering different values during different runs of program."
},
{
"code": null,
"e": 2401,
"s": 2250,
"text": "It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function."
},
{
"code": null,
"e": 2512,
"s": 2401,
"text": "Following is a C program to calculate sum and product of all elements in an array using run time compilation −"
},
{
"code": null,
"e": 2523,
"s": 2512,
"text": " Live Demo"
},
{
"code": null,
"e": 3514,
"s": 2523,
"text": "#include<stdio.h>\nvoid main(){\n //Declaring the array - run time//\n int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];\n //Reading elements into the array's A and B using for loop//\n printf(\"Enter elements into the array A: \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n printf(\"A[%d][%d] :\",i,j);\n scanf(\"%d\",&A[i][j]);\n }\n printf(\"\\n\");\n }\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n printf(\"B[%d][%d] :\",i,j);\n scanf(\"%d\",&B[i][j]);\n }\n printf(\"\\n\");\n }\n //Calculating sum and printing output//\n printf(\"Sum array is : \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n sum[i][j]=A[i][j]+B[i][j];\n printf(\"%d\\t\",sum[i][j]);\n }\n printf(\"\\n\");\n }\n //Calculating product and printing output//\n printf(\"Product array is : \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n product[i][j]=A[i][j]*B[i][j];\n printf(\"%d\\t\",product[i][j]);\n }\n printf(\"\\n\");\n }\n}"
},
{
"code": null,
"e": 3709,
"s": 3514,
"text": "Enter elements into the array A:\nA[0][0] :A[0][1] :A[0][2] :\nA[1][0] :A[1][1] :A[1][2] :\nB[0][0] :B[0][1] :B[0][2] :\nB[1][0] :B[1][1] :B[1][2] :\nSum array is :\n000\n000\nProduct array is :\n000\n000"
}
]
|
How to Convert Char to String in Java? - GeeksforGeeks | 02 Mar, 2022
If we have a char value like ‘G’ and we want to convert it into an equivalent String like “G” then we can do this by using any of the following four listed methods in Java:
Illustration:
Input : 'G'
Output : "G"
Methods:
There are various methods by which we can convert the required character to string with the usage of wrapper classes and methods been provided in java classes.
Using concatenation of stringsUsing toString() method of Character classUsing Character wrapper classUsing valueOf() method of String class
Using concatenation of strings
Using toString() method of Character class
Using Character wrapper class
Using valueOf() method of String class
Let us discuss these methods in detail below as follows with clean java programs as follows:
Method 1: Using concatenation of strings
We can convert a char to a string object in java by concatenating the given character with an empty string .
Example
Java
// Java Program to Convert Char to String// Using Concatenation in Strings // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Concatenating the char variable // with an empty string String s = "" + c; // Print and display the above string System.out.println( "Char to String using Concatenation :" + " " + s); }}
Char to String using Concatenation : G
Method 2: Using toString() method of Character class
We can convert a char to a string object in java by using the Character.toString() method.
Example
Java
// Java Program to Convert Char to String// Using toString() method of Character class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting the char to String using toString // method of Character class and storing it in a // string String s = Character.toString(c); // Print and display the above string System.out.println( "Char to String using Character.toString method :" + " " + s); }}
Char to String using Character.toString method : G
Method 3: Using Character wrapper class
We can convert a char to a string object in java by using java.lang.Character class, which is a wrapper for char primitive type.
Note: This method may arise a warning due to the new keyword as Character(char) in Character has been deprecated and marked for removal.
Example
Java
// Java Program to Convert Char to String// Using toString() method of Character class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting the char to String using toString // method of Character class and storing it in a // string String s = Character.toString(c); // Print and display the above string System.out.println( "Char to String using Character.toString method :" + " " + s); }}
Method 4-A: Using String.valueOf() method of String class
We can convert a char to a string object in java by using String.valueOf(char[]) method.
Example
Java
// Java Program to Convert Char to String// Using String.valueOf() method of String class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting char to String by // using String.valueOf() method String s = String.valueOf(new char[] { c }); // Print and display the above-stored string System.out.println( "Char to String using String.valueOf(new char[]) method :" + " " + s); }}
Char to String using String.valueOf(new char[]) method : G
Method 4-B: Using valueOf() method of String class
We can convert a char to a string object in java by using String.valueOf() method.
Example
Java
// Java Program to Convert Char to String// Using valueOf() method of String class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting char to String // using String.valueOf() method String s = String.valueOf(c); // Print and display the String s System.out.println( "Char to String using String.valueOf() method :" + " " + s); }}
Char to String using String.valueOf() method : G
avtarkumar719
Java-String-Programs
Picked
TrueGeek-2021
Java
Java Programs
TrueGeek
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23893,
"s": 23865,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 24066,
"s": 23893,
"text": "If we have a char value like ‘G’ and we want to convert it into an equivalent String like “G” then we can do this by using any of the following four listed methods in Java:"
},
{
"code": null,
"e": 24080,
"s": 24066,
"text": "Illustration:"
},
{
"code": null,
"e": 24106,
"s": 24080,
"text": "Input : 'G'\nOutput : \"G\""
},
{
"code": null,
"e": 24115,
"s": 24106,
"text": "Methods:"
},
{
"code": null,
"e": 24275,
"s": 24115,
"text": "There are various methods by which we can convert the required character to string with the usage of wrapper classes and methods been provided in java classes."
},
{
"code": null,
"e": 24415,
"s": 24275,
"text": "Using concatenation of stringsUsing toString() method of Character classUsing Character wrapper classUsing valueOf() method of String class"
},
{
"code": null,
"e": 24446,
"s": 24415,
"text": "Using concatenation of strings"
},
{
"code": null,
"e": 24489,
"s": 24446,
"text": "Using toString() method of Character class"
},
{
"code": null,
"e": 24519,
"s": 24489,
"text": "Using Character wrapper class"
},
{
"code": null,
"e": 24558,
"s": 24519,
"text": "Using valueOf() method of String class"
},
{
"code": null,
"e": 24651,
"s": 24558,
"text": "Let us discuss these methods in detail below as follows with clean java programs as follows:"
},
{
"code": null,
"e": 24693,
"s": 24651,
"text": "Method 1: Using concatenation of strings "
},
{
"code": null,
"e": 24804,
"s": 24693,
"text": "We can convert a char to a string object in java by concatenating the given character with an empty string ."
},
{
"code": null,
"e": 24812,
"s": 24804,
"text": "Example"
},
{
"code": null,
"e": 24817,
"s": 24812,
"text": "Java"
},
{
"code": "// Java Program to Convert Char to String// Using Concatenation in Strings // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Concatenating the char variable // with an empty string String s = \"\" + c; // Print and display the above string System.out.println( \"Char to String using Concatenation :\" + \" \" + s); }}",
"e": 25377,
"s": 24817,
"text": null
},
{
"code": null,
"e": 25419,
"s": 25380,
"text": "Char to String using Concatenation : G"
},
{
"code": null,
"e": 25475,
"s": 25421,
"text": "Method 2: Using toString() method of Character class "
},
{
"code": null,
"e": 25570,
"s": 25477,
"text": "We can convert a char to a string object in java by using the Character.toString() method."
},
{
"code": null,
"e": 25580,
"s": 25572,
"text": "Example"
},
{
"code": null,
"e": 25587,
"s": 25582,
"text": "Java"
},
{
"code": "// Java Program to Convert Char to String// Using toString() method of Character class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting the char to String using toString // method of Character class and storing it in a // string String s = Character.toString(c); // Print and display the above string System.out.println( \"Char to String using Character.toString method :\" + \" \" + s); }}",
"e": 26235,
"s": 25587,
"text": null
},
{
"code": null,
"e": 26289,
"s": 26238,
"text": "Char to String using Character.toString method : G"
},
{
"code": null,
"e": 26331,
"s": 26291,
"text": "Method 3: Using Character wrapper class"
},
{
"code": null,
"e": 26465,
"s": 26333,
"text": "We can convert a char to a string object in java by using java.lang.Character class, which is a wrapper for char primitive type."
},
{
"code": null,
"e": 26604,
"s": 26467,
"text": "Note: This method may arise a warning due to the new keyword as Character(char) in Character has been deprecated and marked for removal."
},
{
"code": null,
"e": 26614,
"s": 26606,
"text": "Example"
},
{
"code": null,
"e": 26621,
"s": 26616,
"text": "Java"
},
{
"code": "// Java Program to Convert Char to String// Using toString() method of Character class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting the char to String using toString // method of Character class and storing it in a // string String s = Character.toString(c); // Print and display the above string System.out.println( \"Char to String using Character.toString method :\" + \" \" + s); }}",
"e": 27269,
"s": 26621,
"text": null
},
{
"code": null,
"e": 27332,
"s": 27274,
"text": "Method 4-A: Using String.valueOf() method of String class"
},
{
"code": null,
"e": 27426,
"s": 27334,
"text": "We can convert a char to a string object in java by using String.valueOf(char[]) method."
},
{
"code": null,
"e": 27436,
"s": 27428,
"text": "Example"
},
{
"code": null,
"e": 27443,
"s": 27438,
"text": "Java"
},
{
"code": "// Java Program to Convert Char to String// Using String.valueOf() method of String class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting char to String by // using String.valueOf() method String s = String.valueOf(new char[] { c }); // Print and display the above-stored string System.out.println( \"Char to String using String.valueOf(new char[]) method :\" + \" \" + s); }}",
"e": 28071,
"s": 27443,
"text": null
},
{
"code": null,
"e": 28133,
"s": 28074,
"text": "Char to String using String.valueOf(new char[]) method : G"
},
{
"code": null,
"e": 28187,
"s": 28135,
"text": "Method 4-B: Using valueOf() method of String class "
},
{
"code": null,
"e": 28275,
"s": 28189,
"text": "We can convert a char to a string object in java by using String.valueOf() method."
},
{
"code": null,
"e": 28285,
"s": 28277,
"text": "Example"
},
{
"code": null,
"e": 28292,
"s": 28287,
"text": "Java"
},
{
"code": "// Java Program to Convert Char to String// Using valueOf() method of String class // Importing the required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring a char variable char c = 'G'; // Converting char to String // using String.valueOf() method String s = String.valueOf(c); // Print and display the String s System.out.println( \"Char to String using String.valueOf() method :\" + \" \" + s); }}",
"e": 28879,
"s": 28292,
"text": null
},
{
"code": null,
"e": 28931,
"s": 28882,
"text": "Char to String using String.valueOf() method : G"
},
{
"code": null,
"e": 28947,
"s": 28933,
"text": "avtarkumar719"
},
{
"code": null,
"e": 28968,
"s": 28947,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 28975,
"s": 28968,
"text": "Picked"
},
{
"code": null,
"e": 28989,
"s": 28975,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 28994,
"s": 28989,
"text": "Java"
},
{
"code": null,
"e": 29008,
"s": 28994,
"text": "Java Programs"
},
{
"code": null,
"e": 29017,
"s": 29008,
"text": "TrueGeek"
},
{
"code": null,
"e": 29022,
"s": 29017,
"text": "Java"
},
{
"code": null,
"e": 29120,
"s": 29022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29129,
"s": 29120,
"text": "Comments"
},
{
"code": null,
"e": 29142,
"s": 29129,
"text": "Old Comments"
},
{
"code": null,
"e": 29163,
"s": 29142,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29178,
"s": 29163,
"text": "Stream In Java"
},
{
"code": null,
"e": 29197,
"s": 29178,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29243,
"s": 29197,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29273,
"s": 29243,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29317,
"s": 29273,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 29343,
"s": 29317,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29377,
"s": 29343,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29424,
"s": 29377,
"text": "Implementing a Linked List in Java using Class"
}
]
|
Add new header files in Arduino IDE | Sometimes, you may feel the need to define your own custom header files, for organizing your code better. Say you want to create a global_variables.h file for storing all your global variables.
You can create the file within Arduino IDE by clicking on the bottom arrow at the top right of the screen, and selecting 'New Tab'. (Alternatively, you can press Ctrl+Shift+N on your keyboard)
Name your file in the prompt and press OK.
The new file gets created, and can be found in your Sketch folder.
In order to include this file in your main .ino code, you can simply add the following line at the top of your application −
#include "global_variables.h"
You can replace global_variables.h with the file name you provided in the prompt.
Now you can go ahead and add all global variables in this new .h file. In general, this feature helps a lot when you try to organize lengthy codes. | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Sometimes, you may feel the need to define your own custom header files, for organizing your code better. Say you want to create a global_variables.h file for storing all your global variables."
},
{
"code": null,
"e": 1449,
"s": 1256,
"text": "You can create the file within Arduino IDE by clicking on the bottom arrow at the top right of the screen, and selecting 'New Tab'. (Alternatively, you can press Ctrl+Shift+N on your keyboard)"
},
{
"code": null,
"e": 1492,
"s": 1449,
"text": "Name your file in the prompt and press OK."
},
{
"code": null,
"e": 1559,
"s": 1492,
"text": "The new file gets created, and can be found in your Sketch folder."
},
{
"code": null,
"e": 1684,
"s": 1559,
"text": "In order to include this file in your main .ino code, you can simply add the following line at the top of your application −"
},
{
"code": null,
"e": 1714,
"s": 1684,
"text": "#include \"global_variables.h\""
},
{
"code": null,
"e": 1796,
"s": 1714,
"text": "You can replace global_variables.h with the file name you provided in the prompt."
},
{
"code": null,
"e": 1944,
"s": 1796,
"text": "Now you can go ahead and add all global variables in this new .h file. In general, this feature helps a lot when you try to organize lengthy codes."
}
]
|
Longest Even Length Substring | Practice | GeeksforGeeks | For given string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case contains a string string of length N.
Output:
Print length of the longest substring of length 2k such that sum of left k elements is equal to right k elements and if there is no such substring print 0.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
Example:
Input:
2
000000
1234123
Output:
6
4
0
pushpendrakadwa20182 months ago
class st: def substring(self,s): li=[] for i in range (0,len(s)): for j in range(0,len(s)): a="" a=a+s[i:j+1] if a!="": p=a if len(p)%2==0: lsum=0 rsum=0 for q in range(0,len(p)): if q<len(p)/2: lsum=lsum+int(p[q]) else: rsum=rsum+int(p[q]) if lsum==rsum: li.append(a) if len(li)==0: return 0 else: li.sort(key = len) return len(li[len(li)-1]) #driver code if __name__ == '__main__': T=int(input()) for i in range(0,T): k=input() ob=st() print(ob.substring(k))
0
lindan1233 months ago
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
string str;
int left=0;
int c=0;
int right = 0;
int maxx=0;
cin>>str;
int n = str.length();
if(n==1)
{
cout<<0<<endl;
}
else{
for(int i=0;i<n;i++)
{
int j = i;
int k = i+1;
left=0;
right=0;
while(j>=0 && k<n)
{
left += str[j]-'0';
right += str[k] - '0';
if(left==right)
{
maxx = max(maxx,k-j+1);
}
j--;
k++;
}
}
cout<<maxx<<endl;
}
}
return 0;
}
Time Taken : 0.0
Cpp
+1
vsdrajput0273 months ago
#include <iostream>#include <string>using namespace std;
int longestEvenSubstring(string str){
int maxLength = 0; while (!str.empty()) { int lsum = 0, rsum = 0; for (int i = 0; i < str.length() / 2; i++) { lsum += int(str[i]) - '0'; rsum = 0; int j = i + 1; while ((2 * i + 1 < str.length()) && (j <= 2 * i + 1)) { rsum += int(str[j]) - '0'; j++; } if (lsum == rsum) { maxLength = max(maxLength, 2 * (i + 1)); } } str = str.substr(1); }
return maxLength;}int main(){ int t; cin >> t; cin.ignore(); while (t--) { string str; getline(cin, str); cout << longestEvenSubstring(str) << endl; }
return 0;}
0
gauravsingh9118054 months ago
int n,i,len,ans=0,j; string s; cin>>s; n=s.size(); int pre[n+1]; pre[0]=0; for(i=0;i<n;i++){ pre[i+1]=pre[i]+(s[i]-'0'); } len=(n/2)*2; while(len>=2){ for(i=0;i+len-1<n;i++){ j=i+len-1; if(pre[(i+j)/2+1]-pre[i]==pre[j+1]-pre[(i+j)/2+1]){ ans=len;break; } } if(ans!=0){ break; } len-=2; } cout<<ans<<"\n";
+3
parasmovaliya43214 months ago
#include <iostream>using namespace std;
int main(){int t,i;cin>>t;string s;while(t--){ cin>>s; int n=s.size(),m=0,t1=0,t2=0,k,j; for(i=1;i<n;i++) { t1=0,t2=0; j=i-1; k=i; while(j>=0&&k<=n-1) { t1+=s[j]-48; t2+=s[k]-48; if(t1==t2) m=max(m,k-j+1); j--; k++; } } cout<<m<<endl;}}
0
ayannaskar5067
This comment was deleted.
0
kumarsaket6705 months ago
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) { //code Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0){ int count=0; String str=sc.next();String nw=""; count = findLength(str); System.out.println(count);}}static int findLength(String str){ int len = 0; if(str.length()%2== 0){ len = str.length(); }else{ len = str.length()-1; } for(int i = 0; i<str.length(); i++) { String s = str.substring(i,i+len); int leftsum = 0,rightsum = 0; for(int j = 0 ; j < s.length(); j++){ char a = s.charAt(j); if(j<s.length()/2){ leftsum += Character.getNumericValue(a); }else{ rightsum += Character.getNumericValue(a); } } if(leftsum == rightsum){ // System.out.println(s); return s.length(); } if(i+len == str.length() && len >=2){ i = -1; len = len-2; } } return 0;}}
-5
shindeaniket20720035 months ago
int main() {
+2
rohitpendse1386 months ago
#include <bits/stdc++.h>
#define int long long
using namespace std;
int solve(string &s) {
int ans = 0;
int l, r, lsum, rsum;
int n = s.size();
for (int i = 0; i < n - 1; i++) {
l = i, r = i + 1, lsum = 0, rsum = 0;
while (l >= 0 && r <= n - 1) {
lsum += s[l] - '0';
rsum += s[r] - '0';
if (lsum == rsum) ans = max(ans, r - l + 1);
l--;
r++;
}
}
return ans;
}
int32_t main() {
cin.tie(nullptr);
cout.tie(nullptr);
ios_base::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
cout << solve(s) << '\n';
}
return 0;
}
0
shreyanshmishra27 months ago
class Solution {public static void main (String[] args) { //code Solution ob=new Solution(); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0) { int count=0; String str=sc.next();String nw=""; count=ob.findLength(str); System.out.println(count); }}static int findLength(String str) { int n = str.length(); int maxlen = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j += 2) { int length = j - i + 1; int leftsum = 0, rightsum = 0; for (int k = 0; k < length/2; k++) { leftsum += (str.charAt(i + k) - '0'); rightsum += (str.charAt(i + k + length/2) - '0'); } if (leftsum == rightsum && maxlen < length) maxlen = length; } } return maxlen; }}
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": 436,
"s": 238,
"text": "For given string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.\n "
},
{
"code": null,
"e": 443,
"s": 436,
"text": "Input:"
},
{
"code": null,
"e": 627,
"s": 443,
"text": "The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.\nEach test case contains a string string of length N.\n\nOutput:"
},
{
"code": null,
"e": 783,
"s": 627,
"text": "Print length of the longest substring of length 2k such that sum of left k elements is equal to right k elements and if there is no such substring print 0."
},
{
"code": null,
"e": 797,
"s": 783,
"text": "\nConstraints:"
},
{
"code": null,
"e": 831,
"s": 797,
"text": "1 ≤ T ≤ 100\n1 ≤ N ≤ 100\n\nExample:"
},
{
"code": null,
"e": 855,
"s": 831,
"text": "Input:\n2\n000000\n1234123"
},
{
"code": null,
"e": 869,
"s": 855,
"text": "Output:\n6\n4 "
},
{
"code": null,
"e": 871,
"s": 869,
"text": "0"
},
{
"code": null,
"e": 903,
"s": 871,
"text": "pushpendrakadwa20182 months ago"
},
{
"code": null,
"e": 1787,
"s": 903,
"text": "class st: def substring(self,s): li=[] for i in range (0,len(s)): for j in range(0,len(s)): a=\"\" a=a+s[i:j+1] if a!=\"\": p=a if len(p)%2==0: lsum=0 rsum=0 for q in range(0,len(p)): if q<len(p)/2: lsum=lsum+int(p[q]) else: rsum=rsum+int(p[q]) if lsum==rsum: li.append(a) if len(li)==0: return 0 else: li.sort(key = len) return len(li[len(li)-1]) #driver code if __name__ == '__main__': T=int(input()) for i in range(0,T): k=input() ob=st() print(ob.substring(k)) "
},
{
"code": null,
"e": 1789,
"s": 1787,
"text": "0"
},
{
"code": null,
"e": 1811,
"s": 1789,
"text": "lindan1233 months ago"
},
{
"code": null,
"e": 2581,
"s": 1811,
"text": "#include <iostream>\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int t;\n cin>>t;\n while(t--)\n {\n\t string str;\n\t int left=0;\n\t int c=0;\n\t int right = 0;\n\t int maxx=0;\n\t cin>>str;\n\t int n = str.length();\n\t \n\t if(n==1)\n\t {\n\t cout<<0<<endl;\n\t }\n\t \n\t else{\n\t for(int i=0;i<n;i++)\n\t {\n\t int j = i;\n\t int k = i+1;\n\t left=0;\n\t right=0;\n\t \n\t while(j>=0 && k<n)\n\t {\n\t left += str[j]-'0';\n\t right += str[k] - '0';\n\t if(left==right)\n\t {\n\t maxx = max(maxx,k-j+1);\n\t }\n\t j--;\n\t k++;\n\t }\n\t }\n\t \n\t cout<<maxx<<endl;\n\t }\n\t \n }\n\treturn 0;\n}"
},
{
"code": null,
"e": 2598,
"s": 2581,
"text": "Time Taken : 0.0"
},
{
"code": null,
"e": 2602,
"s": 2598,
"text": "Cpp"
},
{
"code": null,
"e": 2605,
"s": 2602,
"text": "+1"
},
{
"code": null,
"e": 2630,
"s": 2605,
"text": "vsdrajput0273 months ago"
},
{
"code": null,
"e": 2687,
"s": 2630,
"text": "#include <iostream>#include <string>using namespace std;"
},
{
"code": null,
"e": 2725,
"s": 2687,
"text": "int longestEvenSubstring(string str){"
},
{
"code": null,
"e": 3238,
"s": 2725,
"text": " int maxLength = 0; while (!str.empty()) { int lsum = 0, rsum = 0; for (int i = 0; i < str.length() / 2; i++) { lsum += int(str[i]) - '0'; rsum = 0; int j = i + 1; while ((2 * i + 1 < str.length()) && (j <= 2 * i + 1)) { rsum += int(str[j]) - '0'; j++; } if (lsum == rsum) { maxLength = max(maxLength, 2 * (i + 1)); } } str = str.substr(1); }"
},
{
"code": null,
"e": 3422,
"s": 3238,
"text": " return maxLength;}int main(){ int t; cin >> t; cin.ignore(); while (t--) { string str; getline(cin, str); cout << longestEvenSubstring(str) << endl; }"
},
{
"code": null,
"e": 3436,
"s": 3422,
"text": " return 0;}"
},
{
"code": null,
"e": 3438,
"s": 3436,
"text": "0"
},
{
"code": null,
"e": 3468,
"s": 3438,
"text": "gauravsingh9118054 months ago"
},
{
"code": null,
"e": 3886,
"s": 3468,
"text": " int n,i,len,ans=0,j; string s; cin>>s; n=s.size(); int pre[n+1]; pre[0]=0; for(i=0;i<n;i++){ pre[i+1]=pre[i]+(s[i]-'0'); } len=(n/2)*2; while(len>=2){ for(i=0;i+len-1<n;i++){ j=i+len-1; if(pre[(i+j)/2+1]-pre[i]==pre[j+1]-pre[(i+j)/2+1]){ ans=len;break; } } if(ans!=0){ break; } len-=2; } cout<<ans<<\"\\n\";"
},
{
"code": null,
"e": 3889,
"s": 3886,
"text": "+3"
},
{
"code": null,
"e": 3919,
"s": 3889,
"text": "parasmovaliya43214 months ago"
},
{
"code": null,
"e": 3959,
"s": 3919,
"text": "#include <iostream>using namespace std;"
},
{
"code": null,
"e": 4342,
"s": 3959,
"text": "int main(){int t,i;cin>>t;string s;while(t--){ cin>>s; int n=s.size(),m=0,t1=0,t2=0,k,j; for(i=1;i<n;i++) { t1=0,t2=0; j=i-1; k=i; while(j>=0&&k<=n-1) { t1+=s[j]-48; t2+=s[k]-48; if(t1==t2) m=max(m,k-j+1); j--; k++; } } cout<<m<<endl;}}"
},
{
"code": null,
"e": 4344,
"s": 4342,
"text": "0"
},
{
"code": null,
"e": 4359,
"s": 4344,
"text": "ayannaskar5067"
},
{
"code": null,
"e": 4385,
"s": 4359,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4387,
"s": 4385,
"text": "0"
},
{
"code": null,
"e": 4413,
"s": 4387,
"text": "kumarsaket6705 months ago"
},
{
"code": null,
"e": 4469,
"s": 4413,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 5381,
"s": 4469,
"text": "class GFG {public static void main (String[] args) { //code Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0){ int count=0; String str=sc.next();String nw=\"\"; count = findLength(str); System.out.println(count);}}static int findLength(String str){ int len = 0; if(str.length()%2== 0){ len = str.length(); }else{ len = str.length()-1; } for(int i = 0; i<str.length(); i++) { String s = str.substring(i,i+len); int leftsum = 0,rightsum = 0; for(int j = 0 ; j < s.length(); j++){ char a = s.charAt(j); if(j<s.length()/2){ leftsum += Character.getNumericValue(a); }else{ rightsum += Character.getNumericValue(a); } } if(leftsum == rightsum){ // System.out.println(s); return s.length(); } if(i+len == str.length() && len >=2){ i = -1; len = len-2; } } return 0;}}"
},
{
"code": null,
"e": 5384,
"s": 5381,
"text": "-5"
},
{
"code": null,
"e": 5416,
"s": 5384,
"text": "shindeaniket20720035 months ago"
},
{
"code": null,
"e": 5429,
"s": 5416,
"text": "int main() {"
},
{
"code": null,
"e": 5432,
"s": 5429,
"text": "+2"
},
{
"code": null,
"e": 5459,
"s": 5432,
"text": "rohitpendse1386 months ago"
},
{
"code": null,
"e": 6164,
"s": 5459,
"text": "#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nint solve(string &s) {\n int ans = 0;\n int l, r, lsum, rsum;\n int n = s.size();\n for (int i = 0; i < n - 1; i++) {\n l = i, r = i + 1, lsum = 0, rsum = 0;\n while (l >= 0 && r <= n - 1) {\n lsum += s[l] - '0';\n rsum += s[r] - '0';\n if (lsum == rsum) ans = max(ans, r - l + 1);\n l--;\n r++;\n }\n }\n return ans;\n}\n\nint32_t main() {\n cin.tie(nullptr);\n cout.tie(nullptr);\n ios_base::sync_with_stdio(false);\n int t;\n cin >> t;\n while (t--) {\n string s;\n cin >> s;\n cout << solve(s) << '\\n';\n }\n return 0;\n}"
},
{
"code": null,
"e": 6166,
"s": 6164,
"text": "0"
},
{
"code": null,
"e": 6195,
"s": 6166,
"text": "shreyanshmishra27 months ago"
},
{
"code": null,
"e": 7051,
"s": 6195,
"text": "class Solution {public static void main (String[] args) { //code Solution ob=new Solution(); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0) { int count=0; String str=sc.next();String nw=\"\"; count=ob.findLength(str); System.out.println(count); }}static int findLength(String str) { int n = str.length(); int maxlen = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j += 2) { int length = j - i + 1; int leftsum = 0, rightsum = 0; for (int k = 0; k < length/2; k++) { leftsum += (str.charAt(i + k) - '0'); rightsum += (str.charAt(i + k + length/2) - '0'); } if (leftsum == rightsum && maxlen < length) maxlen = length; } } return maxlen; }}"
},
{
"code": null,
"e": 7197,
"s": 7051,
"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": 7233,
"s": 7197,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7243,
"s": 7233,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7253,
"s": 7243,
"text": "\nContest\n"
},
{
"code": null,
"e": 7316,
"s": 7253,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7464,
"s": 7316,
"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": 7672,
"s": 7464,
"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": 7778,
"s": 7672,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
How to make a Tkinter window jump to the front? | In order to make the tkinter window or the root window jump above all the other windows, we can use attributes method that will generally take two values specifying the “topmost” value and the other is a Boolean value.
#Importing the library
from tkinter import *
#Create an instance of tkinter window or frame
win= Tk()
#Setting the geometry of window
win.geometry("600x250")
#Create a Label
Label(win, text= "Hello Everyone!",font=('Helvetica bold',
15)).pack(pady=20)
#Make the window jump above all
win.attributes('-topmost',1)
win.mainloop()
Running the above code will make the window stay above all other windows, | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "In order to make the tkinter window or the root window jump above all the other windows, we can use attributes method that will generally take two values specifying the “topmost” value and the other is a Boolean value."
},
{
"code": null,
"e": 1614,
"s": 1281,
"text": "#Importing the library\nfrom tkinter import *\n\n#Create an instance of tkinter window or frame\nwin= Tk()\n\n#Setting the geometry of window\nwin.geometry(\"600x250\")\n\n#Create a Label\nLabel(win, text= \"Hello Everyone!\",font=('Helvetica bold',\n15)).pack(pady=20)\n\n#Make the window jump above all\nwin.attributes('-topmost',1)\n\nwin.mainloop()"
},
{
"code": null,
"e": 1688,
"s": 1614,
"text": "Running the above code will make the window stay above all other windows,"
}
]
|
Use of explicit keyword in C++
| Here we will see what will be the effect of explicit keyword in C++. Before discussing that, let us see one example code, and try to find out its output.
#include <iostream>
using namespace std;
class Point {
private:
double x, y;
public:
Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
//constructor
}
bool operator==(Point p2) {
if(p2.x == this->x && p2.y == this->y)
return true;
return false;
}
};
int main() {
Point p(5, 0);
if(p == 5)
cout << "They are same";
else
cout << "They are not same";
}
They are same
This is working fine because we know that if one constructor can be called using one argument only, then it will be converted into conversion constructor. But we can avoid this kind of conversion, as this may generate some unreliable results.
To restrict this conversion, we can use the explicit modifier with the constructor. In that case, it will not be converted. If the above program is used using explicit keyword, then it will generate compilation error.
#include <iostream>
using namespace std;
class Point {
private:
double x, y;
public:
explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
//constructor
}
bool operator==(Point p2) {
if(p2.x == this->x && p2.y == this->y)
return true;
return false;
}
};
int main() {
Point p(5, 0);
if(p == 5)
cout << "They are same";
else
cout << "They are not same";
}
[Error] no match for 'operator==' (operand types are 'Point' and 'int')
[Note] candidates are:
[Note] bool Point::operator==(Point)
We can still typecast a value to the Point type by using explicit casting.
#include <iostream>
using namespace std;
class Point {
private:
double x, y;
public:
explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
//constructor
}
bool operator==(Point p2) {
if(p2.x == this->x && p2.y == this->y)
return true;
return false;
}
};
int main() {
Point p(5, 0);
if(p == (Point)5)
cout << "They are same";
else
cout << "They are not same";
}
They are same | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "Here we will see what will be the effect of explicit keyword in C++. Before discussing that, let us see one example code, and try to find out its output."
},
{
"code": null,
"e": 1662,
"s": 1216,
"text": "#include <iostream>\nusing namespace std;\nclass Point {\n private:\n double x, y;\n public:\n Point(double a = 0.0, double b = 0.0) : x(a), y(b) {\n //constructor\n }\n bool operator==(Point p2) {\n if(p2.x == this->x && p2.y == this->y)\n return true;\n return false;\n }\n};\nint main() {\n Point p(5, 0);\n if(p == 5)\n cout << \"They are same\";\n else\n cout << \"They are not same\";\n}"
},
{
"code": null,
"e": 1676,
"s": 1662,
"text": "They are same"
},
{
"code": null,
"e": 1919,
"s": 1676,
"text": "This is working fine because we know that if one constructor can be called using one argument only, then it will be converted into conversion constructor. But we can avoid this kind of conversion, as this may generate some unreliable results."
},
{
"code": null,
"e": 2137,
"s": 1919,
"text": "To restrict this conversion, we can use the explicit modifier with the constructor. In that case, it will not be converted. If the above program is used using explicit keyword, then it will generate compilation error."
},
{
"code": null,
"e": 2592,
"s": 2137,
"text": "#include <iostream>\nusing namespace std;\nclass Point {\n private:\n double x, y;\n public:\n explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {\n //constructor\n }\n bool operator==(Point p2) {\n if(p2.x == this->x && p2.y == this->y)\n return true;\n return false;\n }\n};\nint main() {\n Point p(5, 0);\n if(p == 5)\n cout << \"They are same\";\n else\n cout << \"They are not same\";\n}"
},
{
"code": null,
"e": 2724,
"s": 2592,
"text": "[Error] no match for 'operator==' (operand types are 'Point' and 'int')\n[Note] candidates are:\n[Note] bool Point::operator==(Point)"
},
{
"code": null,
"e": 2799,
"s": 2724,
"text": "We can still typecast a value to the Point type by using explicit casting."
},
{
"code": null,
"e": 3261,
"s": 2799,
"text": "#include <iostream>\nusing namespace std;\nclass Point {\n private:\n double x, y;\n public:\n explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {\n //constructor\n }\n bool operator==(Point p2) {\n if(p2.x == this->x && p2.y == this->y)\n return true;\n return false;\n }\n};\nint main() {\n Point p(5, 0);\n if(p == (Point)5)\n cout << \"They are same\";\n else\n cout << \"They are not same\";\n}"
},
{
"code": null,
"e": 3275,
"s": 3261,
"text": "They are same"
}
]
|
Program to reverse words in a given string in C++ | 11 Jul, 2022
Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples:
Input: str = “the sky is blue” Output: blue is sky theInput: str = “I love programming” Output: programming love I
Method 1: Using STL functions
Reverse the given string str using STL function reverse().Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse().
Reverse the given string str using STL function reverse().
Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse().
Below is the implementation of the above approach:
CPP
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the given stringstring reverseString(string str){ // Reverse str using inbuilt function reverse(str.begin(), str.end()); // Add space at the end so that the // last word is also reversed str.insert(str.end(), ' '); int n = str.length(); int j = 0; // Find spaces and reverse all words // before that for (int i = 0; i < n; i++) { // If a space is encountered if (str[i] == ' ') { reverse(str.begin() + j, str.begin() + i); // Update the starting index // for next word to reverse j = i + 1; } } // Remove spaces from the end of the // word that we appended str.pop_back(); // Return the reversed string return str;} // Driver codeint main(){ string str = "I like this code"; // Function call string rev = reverseString(str); // Print the reversed string cout << rev; return 0;}
code this like I
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2: Without using the inbuilt function: We can create the reverse() function which is used to reverse the given string. Below are the steps:
Initially reverse each word of the given string str.Now reverse the whole string to get the resultant string in desired order.
Initially reverse each word of the given string str.
Now reverse the whole string to get the resultant string in desired order.
Below is the implementation of the above approach:
CPP
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function used to reverse a string// from index l to rvoid reversed(string& s, int l, int r){ while (l < r) { // Swap characters at l and r swap(s[l], s[r]); l++; r--; }} // Function to reverse the given stringstring reverseString(string str){ // Add space at the end so that the // last word is also reversed str.insert(str.end(), ' '); int n = str.length(); int j = 0; // Find spaces and reverse all words // before that for (int i = 0; i < n; i++) { // If a space is encountered if (str[i] == ' ') { // Function call to our custom // reverse function() reversed(str, j, i - 1); // Update the starting index // for next word to reverse j = i + 1; } } // Remove spaces from the end of the // word that we appended str.pop_back(); // Reverse the whole string reversed(str, 0, str.length() - 1); // Return the reversed string return str;} // Driver codeint main(){ string str = "I like this code"; // Function call string rev = reverseString(str); // Print the reversed string cout << rev; return 0;}
code this like I
Time Complexity: O(n2) Auxiliary Space: O(1)
Method – 3 : Without Using Extra Space
The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.
C++
// C++ code to reverse a string#include <bits/stdc++.h>using namespace std; // Reverse the stringstring RevString(string s[], int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + " " + s[i]; } return S;} // Driver codeint main(){ string s = "getting good at coding " "needs a lot of practice"; string words[] = { "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice" }; cout << RevString(words, 9) << endl; return 0;} // This code is contributed by AJAY MAKVANA
practice of lot a needs coding at good getting
Time Complexity: O(n)
Auxiliary Space: O(n)
simranarora5sos
pankajsharmagfg
sweetyty
ajaymakvana
polymatir3j
cpp-strings
Reverse
STL
C++ Programs
Data Structures
Strings
cpp-strings
Data Structures
Strings
STL
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 173,
"s": 54,
"text": "Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples: "
},
{
"code": null,
"e": 290,
"s": 173,
"text": "Input: str = “the sky is blue” Output: blue is sky theInput: str = “I love programming” Output: programming love I "
},
{
"code": null,
"e": 324,
"s": 292,
"text": "Method 1: Using STL functions "
},
{
"code": null,
"e": 509,
"s": 324,
"text": "Reverse the given string str using STL function reverse().Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse()."
},
{
"code": null,
"e": 568,
"s": 509,
"text": "Reverse the given string str using STL function reverse()."
},
{
"code": null,
"e": 695,
"s": 568,
"text": "Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse()."
},
{
"code": null,
"e": 747,
"s": 695,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 751,
"s": 747,
"text": "CPP"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the given stringstring reverseString(string str){ // Reverse str using inbuilt function reverse(str.begin(), str.end()); // Add space at the end so that the // last word is also reversed str.insert(str.end(), ' '); int n = str.length(); int j = 0; // Find spaces and reverse all words // before that for (int i = 0; i < n; i++) { // If a space is encountered if (str[i] == ' ') { reverse(str.begin() + j, str.begin() + i); // Update the starting index // for next word to reverse j = i + 1; } } // Remove spaces from the end of the // word that we appended str.pop_back(); // Return the reversed string return str;} // Driver codeint main(){ string str = \"I like this code\"; // Function call string rev = reverseString(str); // Print the reversed string cout << rev; return 0;}",
"e": 1796,
"s": 751,
"text": null
},
{
"code": null,
"e": 1813,
"s": 1796,
"text": "code this like I"
},
{
"code": null,
"e": 1837,
"s": 1813,
"text": "Time Complexity: O(n2) "
},
{
"code": null,
"e": 1859,
"s": 1837,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2008,
"s": 1859,
"text": "Method 2: Without using the inbuilt function: We can create the reverse() function which is used to reverse the given string. Below are the steps: "
},
{
"code": null,
"e": 2135,
"s": 2008,
"text": "Initially reverse each word of the given string str.Now reverse the whole string to get the resultant string in desired order."
},
{
"code": null,
"e": 2188,
"s": 2135,
"text": "Initially reverse each word of the given string str."
},
{
"code": null,
"e": 2263,
"s": 2188,
"text": "Now reverse the whole string to get the resultant string in desired order."
},
{
"code": null,
"e": 2315,
"s": 2263,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2319,
"s": 2315,
"text": "CPP"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function used to reverse a string// from index l to rvoid reversed(string& s, int l, int r){ while (l < r) { // Swap characters at l and r swap(s[l], s[r]); l++; r--; }} // Function to reverse the given stringstring reverseString(string str){ // Add space at the end so that the // last word is also reversed str.insert(str.end(), ' '); int n = str.length(); int j = 0; // Find spaces and reverse all words // before that for (int i = 0; i < n; i++) { // If a space is encountered if (str[i] == ' ') { // Function call to our custom // reverse function() reversed(str, j, i - 1); // Update the starting index // for next word to reverse j = i + 1; } } // Remove spaces from the end of the // word that we appended str.pop_back(); // Reverse the whole string reversed(str, 0, str.length() - 1); // Return the reversed string return str;} // Driver codeint main(){ string str = \"I like this code\"; // Function call string rev = reverseString(str); // Print the reversed string cout << rev; return 0;}",
"e": 3605,
"s": 2319,
"text": null
},
{
"code": null,
"e": 3622,
"s": 3605,
"text": "code this like I"
},
{
"code": null,
"e": 3668,
"s": 3622,
"text": "Time Complexity: O(n2) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 3707,
"s": 3668,
"text": "Method – 3 : Without Using Extra Space"
},
{
"code": null,
"e": 3879,
"s": 3707,
"text": "The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too."
},
{
"code": null,
"e": 3883,
"s": 3879,
"text": "C++"
},
{
"code": "// C++ code to reverse a string#include <bits/stdc++.h>using namespace std; // Reverse the stringstring RevString(string s[], int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + \" \" + s[i]; } return S;} // Driver codeint main(){ string s = \"getting good at coding \" \"needs a lot of practice\"; string words[] = { \"getting\", \"good\", \"at\", \"coding\", \"needs\", \"a\", \"lot\", \"of\", \"practice\" }; cout << RevString(words, 9) << endl; return 0;} // This code is contributed by AJAY MAKVANA",
"e": 5279,
"s": 3883,
"text": null
},
{
"code": null,
"e": 5326,
"s": 5279,
"text": "practice of lot a needs coding at good getting"
},
{
"code": null,
"e": 5349,
"s": 5326,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 5387,
"s": 5371,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5403,
"s": 5387,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 5412,
"s": 5403,
"text": "sweetyty"
},
{
"code": null,
"e": 5424,
"s": 5412,
"text": "ajaymakvana"
},
{
"code": null,
"e": 5436,
"s": 5424,
"text": "polymatir3j"
},
{
"code": null,
"e": 5448,
"s": 5436,
"text": "cpp-strings"
},
{
"code": null,
"e": 5456,
"s": 5448,
"text": "Reverse"
},
{
"code": null,
"e": 5460,
"s": 5456,
"text": "STL"
},
{
"code": null,
"e": 5473,
"s": 5460,
"text": "C++ Programs"
},
{
"code": null,
"e": 5489,
"s": 5473,
"text": "Data Structures"
},
{
"code": null,
"e": 5497,
"s": 5489,
"text": "Strings"
},
{
"code": null,
"e": 5509,
"s": 5497,
"text": "cpp-strings"
},
{
"code": null,
"e": 5525,
"s": 5509,
"text": "Data Structures"
},
{
"code": null,
"e": 5533,
"s": 5525,
"text": "Strings"
},
{
"code": null,
"e": 5537,
"s": 5533,
"text": "STL"
},
{
"code": null,
"e": 5545,
"s": 5537,
"text": "Reverse"
}
]
|
Introduction To PYTHON | 07 Jul, 2022
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/ that can be used to run Python programs without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/.
Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number.
macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/.
2) Writing our first program:
Just type in the following code after you start the interpreter.
# Script Begins print("GeeksQuiz") # Scripts Ends
Output:
GeeksQuiz
Let’s analyze the script line by line.
Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by the interpreter and serves as documentation for our code.
Line 2: [print(“GeeksQuiz”)] To print something on the console, print() function is used. This function also adds a newline after our message is printed(unlike in C). Note that in Python 2, “print” is not a function but a keyword and therefore can be used without parentheses. However, in Python 3, it is a function and must be invoked with parentheses.
Line 3: [# Script Ends] This is just another comment like in Line 1.
Introduction to Python | Sample Video for Python Foundation Course | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersIntroduction to Python | Sample Video for Python Foundation Course | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KWnoiOimNbs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language.
Prerequisites:
Knowledge of any programming language can be a plus.
Reason for increasing popularity
Emphasis on code readability, shorter codes, ease of writingProgrammers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.There exists inbuilt functions for almost all of the frequently used concepts.Philosophy is “Simplicity is the best”.
Emphasis on code readability, shorter codes, ease of writing
Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
There exists inbuilt functions for almost all of the frequently used concepts.
Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES
InterpretedThere are no separate compilation and execution steps like C and C++.Directly run the program from the source code.Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.No need to worry about linking and loading with libraries, etc.
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.
No need to worry about linking and loading with libraries, etc.
Platform IndependentPython programs can be developed and executed on multiple operating system platforms.Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Python programs can be developed and executed on multiple operating system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source; Redistributable
High-level LanguageIn Python, no need to take care about low-level details such as managing the memory used by the program.
In Python, no need to take care about low-level details such as managing the memory used by the program.
SimpleCloser to English language;Easy to LearnMore emphasis on the solution to the problem rather than the syntax
Closer to English language;Easy to Learn
More emphasis on the solution to the problem rather than the syntax
EmbeddablePython can be used within C/C++ program to give scripting capabilities for the program’s users.
Python can be used within C/C++ program to give scripting capabilities for the program’s users.
Robust:Exceptional handling featuresMemory management techniques in built
Exceptional handling features
Memory management techniques in built
Rich Library SupportThe Python Standard Library is very vast.Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
The Python Standard Library is very vast.
Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
Python vs JAVA
Python
Java
Dynamically Typed
No need to declare anything. An assignment statement binds a name to an object, and the object can be of any type.
No type casting is required when using container objects
Statically Typed
All variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception.
Type casting is required when using container objects.
The classical Hello World program illustrating the relative verbosity of a Java Program and Python ProgramJava Code
public class HelloWorld{ public static void main (String[] args) { System.out.println("Hello, world!"); }}
Python Code
print("Hello, world!")
Similarity with Java
Require some form of runtime on your system (JVM/Python runtime)
Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)
LOOK and FEEL of the Python
GUI
Command Line interface
Softwares making use of Python
Python has been successfully embedded in a number of software products as a scripting language.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.Python has also been used in artificial intelligencePython is often used for natural language processing tasks.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.
Python has also been used in artificial intelligence
Python is often used for natural language processing tasks.
Current Applications of Python
A number of Linux distributions use installers written in Python example in Ubuntu we have the UbiquityPython has seen extensive use in the information security industry, including in exploit development.Raspberry Pi– single board computer uses Python as its principal user-programming language.Python is now being used Game Development areas also.
A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity
Python has seen extensive use in the information security industry, including in exploit development.
Raspberry Pi– single board computer uses Python as its principal user-programming language.
Python is now being used Game Development areas also.
Pros:
Ease of useMulti-paradigm Approach
Ease of use
Multi-paradigm Approach
Cons:
Slow speed of execution compared to C,C++Absence from mobile computing and browsersFor the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Slow speed of execution compared to C,C++
Absence from mobile computing and browsers
For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it.
Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management.
Presence of third-party modules Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) Open source and community development Versatile, Easy to read, learn and writeUser-friendly data structures High-level language Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) Object-oriented language Portable and InteractiveIdeal for prototypes – provide more functionality with less codingHighly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)(IoT)Internet of Things OpportunitiesInterpreted LanguagePortable across Operating systems
Presence of third-party modules
Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc)
Open source and community development
Versatile, Easy to read, learn and write
User-friendly data structures
High-level language
Dynamically typed language(No need to mention data type based on the value assigned, it takes data type)
Object-oriented language
Portable and Interactive
Ideal for prototypes – provide more functionality with less coding
Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)
(IoT)Internet of Things Opportunities
Interpreted Language
Portable across Operating systems
GUI based desktop applicationsGraphic design, image processing applications, Games, and Scientific/ computational ApplicationsWeb frameworks and applications Enterprise and Business applications Operating Systems EducationDatabase AccessLanguage Development Prototyping Software Development
GUI based desktop applications
Graphic design, image processing applications, Games, and Scientific/ computational Applications
Web frameworks and applications
Enterprise and Business applications
Operating Systems
Education
Database Access
Language Development
Prototyping
Software Development
Organizations using Python :
Google(Components of Google spider and Search Engine) Yahoo(Maps) YouTube Mozilla Dropbox Microsoft Cisco Spotify Quora
Google(Components of Google spider and Search Engine)
Yahoo(Maps)
YouTube
Mozilla
Dropbox
Microsoft
Cisco
Spotify
Quora
So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, Java ( I have taken these 3 because they are most famous and mostly used languages).
# Python code for "Hello World"# nothing else to type...see how simple is the syntax. print("Hello World")
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope.Now moving on further Lets start our basics of Python . I will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
Introduction and Setup
If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :The ” >>> ” represents the python shell and its ready to take python commands and code.Variables and Data StructuresIn other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.# Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber ="helloworld"print(myNumber)Output:3
4.5
helloworld
See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list.# Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append("String") print(nums)Output:[21, 40.5, String]Comments:# is used for single line comment in Python
""" this is a comment """ is used for multi line commentsInput and OutputIn this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.# Python program to illustrate# getting input from username = input("Enter your name: ") # user entered the name 'harssh'print("hello", name)Output:hello harssh # Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input("Enter num1: "))num2 = int(input("Enter num2: ")) num3 = num1 * num2print("Product is: ", num3)Output:Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
SelectionSelection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)# Python program to illustrate# selection statement num1 = 34if(num1>12): print("Num1 is good")elif(num1>35): print("Num2 is not gooooo....")else: print("Num2 is great")Output:Num1 is goodFunctionsYou can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:def function-name(arguments):
#function body# Python program to illustrate# functionsdef hello(): print("hello") print("hello again")hello() # calling functionhello() Output:hello
hello again
hello
hello again
Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages.# Python program to illustrate # function with maindef getInteger(): result = int(input("Enter integer: ")) return result def Main(): print("Started") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__=="__main__": Main()Output:Started
Enter integer: 5
Iteration (Looping)As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.# Python program to illustrate# a simple for loop for step in range(5): print(step)Output:0
1
2
3
4
ModulesPython has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.# Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__=="__main__": Main()Output:85.0Related CoursesPython Programming Foundation -Self Paced CourseNew to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today.DS Using Python Programming – Self Paced CourseIf you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today.My Personal Notes
arrow_drop_upSave
If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :
It will look somehow this :
If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :
The ” >>> ” represents the python shell and its ready to take python commands and code.
Variables and Data Structures
In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.
# Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber ="helloworld"print(myNumber)
Output:
3
4.5
helloworld
See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list.
# Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append("String") print(nums)
Output:
[21, 40.5, String]
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.
# Python program to illustrate# getting input from username = input("Enter your name: ") # user entered the name 'harssh'print("hello", name)
Output:
hello harssh
# Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input("Enter num1: "))num2 = int(input("Enter num2: ")) num3 = num1 * num2print("Product is: ", num3)
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)
# Python program to illustrate# selection statement num1 = 34if(num1>12): print("Num1 is good")elif(num1>35): print("Num2 is not gooooo....")else: print("Num2 is great")
Output:
Num1 is good
Functions
You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:
def function-name(arguments):
#function body
# Python program to illustrate# functionsdef hello(): print("hello") print("hello again")hello() # calling functionhello()
Output:
hello
hello again
hello
hello again
Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages.
# Python program to illustrate # function with maindef getInteger(): result = int(input("Enter integer: ")) return result def Main(): print("Started") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__=="__main__": Main()
Output:
Started
Enter integer: 5
Iteration (Looping)
As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.
# Python program to illustrate# a simple for loop for step in range(5): print(step)
Output:
0
1
2
3
4
Modules
Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.
# Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__=="__main__": Main()
Output:
85.0
New to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today.
If you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today.
shivamsaraswat
lalitshankarch
sarajadhav12052009
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Reverse a string in Java
Arrays in C/C++
Interfaces in Java
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 365,
"s": 53,
"text": "Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code."
},
{
"code": null,
"e": 465,
"s": 365,
"text": "Python is a programming language that lets you work quickly and integrate systems more efficiently."
},
{
"code": null,
"e": 551,
"s": 465,
"text": "There are two major Python versions: Python 2 and Python 3. Both are quite different."
},
{
"code": null,
"e": 586,
"s": 551,
"text": "Beginning with Python programming:"
},
{
"code": null,
"e": 613,
"s": 586,
"text": "1) Finding an Interpreter:"
},
{
"code": null,
"e": 864,
"s": 613,
"text": "Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/ that can be used to run Python programs without installing an interpreter."
},
{
"code": null,
"e": 1067,
"s": 864,
"text": "Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/."
},
{
"code": null,
"e": 1302,
"s": 1067,
"text": "Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number."
},
{
"code": null,
"e": 1423,
"s": 1302,
"text": "macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/."
},
{
"code": null,
"e": 1453,
"s": 1423,
"text": "2) Writing our first program:"
},
{
"code": null,
"e": 1518,
"s": 1453,
"text": "Just type in the following code after you start the interpreter."
},
{
"code": "# Script Begins print(\"GeeksQuiz\") # Scripts Ends",
"e": 1570,
"s": 1518,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Output:"
},
{
"code": null,
"e": 1588,
"s": 1578,
"text": "GeeksQuiz"
},
{
"code": null,
"e": 1627,
"s": 1588,
"text": "Let’s analyze the script line by line."
},
{
"code": null,
"e": 1776,
"s": 1627,
"text": "Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by the interpreter and serves as documentation for our code."
},
{
"code": null,
"e": 2130,
"s": 1776,
"text": "Line 2: [print(“GeeksQuiz”)] To print something on the console, print() function is used. This function also adds a newline after our message is printed(unlike in C). Note that in Python 2, “print” is not a function but a keyword and therefore can be used without parentheses. However, in Python 3, it is a function and must be invoked with parentheses."
},
{
"code": null,
"e": 2199,
"s": 2130,
"text": "Line 3: [# Script Ends] This is just another comment like in Line 1."
},
{
"code": null,
"e": 3149,
"s": 2199,
"text": "Introduction to Python | Sample Video for Python Foundation Course | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersIntroduction to Python | Sample Video for Python Foundation Course | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KWnoiOimNbs\" 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": 3267,
"s": 3149,
"text": "Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language."
},
{
"code": null,
"e": 3282,
"s": 3267,
"text": "Prerequisites:"
},
{
"code": null,
"e": 3335,
"s": 3282,
"text": "Knowledge of any programming language can be a plus."
},
{
"code": null,
"e": 3368,
"s": 3335,
"text": "Reason for increasing popularity"
},
{
"code": null,
"e": 3779,
"s": 3368,
"text": "Emphasis on code readability, shorter codes, ease of writingProgrammers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.There exists inbuilt functions for almost all of the frequently used concepts.Philosophy is “Simplicity is the best”."
},
{
"code": null,
"e": 3840,
"s": 3779,
"text": "Emphasis on code readability, shorter codes, ease of writing"
},
{
"code": null,
"e": 3952,
"s": 3840,
"text": "Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java."
},
{
"code": null,
"e": 4075,
"s": 3952,
"text": "Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural."
},
{
"code": null,
"e": 4154,
"s": 4075,
"text": "There exists inbuilt functions for almost all of the frequently used concepts."
},
{
"code": null,
"e": 4194,
"s": 4154,
"text": "Philosophy is “Simplicity is the best”."
},
{
"code": null,
"e": 4212,
"s": 4194,
"text": "LANGUAGE FEATURES"
},
{
"code": null,
"e": 4566,
"s": 4212,
"text": "InterpretedThere are no separate compilation and execution steps like C and C++.Directly run the program from the source code.Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.No need to worry about linking and loading with libraries, etc."
},
{
"code": null,
"e": 4636,
"s": 4566,
"text": "There are no separate compilation and execution steps like C and C++."
},
{
"code": null,
"e": 4683,
"s": 4636,
"text": "Directly run the program from the source code."
},
{
"code": null,
"e": 4848,
"s": 4683,
"text": "Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it."
},
{
"code": null,
"e": 4912,
"s": 4848,
"text": "No need to worry about linking and loading with libraries, etc."
},
{
"code": null,
"e": 5089,
"s": 4912,
"text": "Platform IndependentPython programs can be developed and executed on multiple operating system platforms.Python can be used on Linux, Windows, Macintosh, Solaris and many more."
},
{
"code": null,
"e": 5175,
"s": 5089,
"text": "Python programs can be developed and executed on multiple operating system platforms."
},
{
"code": null,
"e": 5247,
"s": 5175,
"text": "Python can be used on Linux, Windows, Macintosh, Solaris and many more."
},
{
"code": null,
"e": 5285,
"s": 5247,
"text": "Free and Open Source; Redistributable"
},
{
"code": null,
"e": 5409,
"s": 5285,
"text": "High-level LanguageIn Python, no need to take care about low-level details such as managing the memory used by the program."
},
{
"code": null,
"e": 5514,
"s": 5409,
"text": "In Python, no need to take care about low-level details such as managing the memory used by the program."
},
{
"code": null,
"e": 5628,
"s": 5514,
"text": "SimpleCloser to English language;Easy to LearnMore emphasis on the solution to the problem rather than the syntax"
},
{
"code": null,
"e": 5669,
"s": 5628,
"text": "Closer to English language;Easy to Learn"
},
{
"code": null,
"e": 5737,
"s": 5669,
"text": "More emphasis on the solution to the problem rather than the syntax"
},
{
"code": null,
"e": 5843,
"s": 5737,
"text": "EmbeddablePython can be used within C/C++ program to give scripting capabilities for the program’s users."
},
{
"code": null,
"e": 5939,
"s": 5843,
"text": "Python can be used within C/C++ program to give scripting capabilities for the program’s users."
},
{
"code": null,
"e": 6013,
"s": 5939,
"text": "Robust:Exceptional handling featuresMemory management techniques in built"
},
{
"code": null,
"e": 6043,
"s": 6013,
"text": "Exceptional handling features"
},
{
"code": null,
"e": 6081,
"s": 6043,
"text": "Memory management techniques in built"
},
{
"code": null,
"e": 6570,
"s": 6081,
"text": "Rich Library SupportThe Python Standard Library is very vast.Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library."
},
{
"code": null,
"e": 6612,
"s": 6570,
"text": "The Python Standard Library is very vast."
},
{
"code": null,
"e": 6872,
"s": 6612,
"text": "Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more."
},
{
"code": null,
"e": 7041,
"s": 6872,
"text": "Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library."
},
{
"code": null,
"e": 7056,
"s": 7041,
"text": "Python vs JAVA"
},
{
"code": null,
"e": 7063,
"s": 7056,
"text": "Python"
},
{
"code": null,
"e": 7068,
"s": 7063,
"text": "Java"
},
{
"code": null,
"e": 7087,
"s": 7068,
"text": "Dynamically Typed "
},
{
"code": null,
"e": 7202,
"s": 7087,
"text": "No need to declare anything. An assignment statement binds a name to an object, and the object can be of any type."
},
{
"code": null,
"e": 7260,
"s": 7202,
"text": "No type casting is required when using container objects"
},
{
"code": null,
"e": 7277,
"s": 7260,
"text": "Statically Typed"
},
{
"code": null,
"e": 7445,
"s": 7277,
"text": "All variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception."
},
{
"code": null,
"e": 7500,
"s": 7445,
"text": "Type casting is required when using container objects."
},
{
"code": null,
"e": 7616,
"s": 7500,
"text": "The classical Hello World program illustrating the relative verbosity of a Java Program and Python ProgramJava Code"
},
{
"code": "public class HelloWorld{ public static void main (String[] args) { System.out.println(\"Hello, world!\"); }}",
"e": 7734,
"s": 7616,
"text": null
},
{
"code": null,
"e": 7746,
"s": 7734,
"text": "Python Code"
},
{
"code": "print(\"Hello, world!\")",
"e": 7769,
"s": 7746,
"text": null
},
{
"code": null,
"e": 7790,
"s": 7769,
"text": "Similarity with Java"
},
{
"code": null,
"e": 7855,
"s": 7790,
"text": "Require some form of runtime on your system (JVM/Python runtime)"
},
{
"code": null,
"e": 7981,
"s": 7855,
"text": "Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)"
},
{
"code": null,
"e": 8009,
"s": 7981,
"text": "LOOK and FEEL of the Python"
},
{
"code": null,
"e": 8013,
"s": 8009,
"text": "GUI"
},
{
"code": null,
"e": 8036,
"s": 8013,
"text": "Command Line interface"
},
{
"code": null,
"e": 8067,
"s": 8036,
"text": "Softwares making use of Python"
},
{
"code": null,
"e": 8163,
"s": 8067,
"text": "Python has been successfully embedded in a number of software products as a scripting language."
},
{
"code": null,
"e": 8370,
"s": 8163,
"text": "GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.Python has also been used in artificial intelligencePython is often used for natural language processing tasks."
},
{
"code": null,
"e": 8466,
"s": 8370,
"text": "GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers."
},
{
"code": null,
"e": 8519,
"s": 8466,
"text": "Python has also been used in artificial intelligence"
},
{
"code": null,
"e": 8579,
"s": 8519,
"text": "Python is often used for natural language processing tasks."
},
{
"code": null,
"e": 8610,
"s": 8579,
"text": "Current Applications of Python"
},
{
"code": null,
"e": 8959,
"s": 8610,
"text": "A number of Linux distributions use installers written in Python example in Ubuntu we have the UbiquityPython has seen extensive use in the information security industry, including in exploit development.Raspberry Pi– single board computer uses Python as its principal user-programming language.Python is now being used Game Development areas also."
},
{
"code": null,
"e": 9063,
"s": 8959,
"text": "A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity"
},
{
"code": null,
"e": 9165,
"s": 9063,
"text": "Python has seen extensive use in the information security industry, including in exploit development."
},
{
"code": null,
"e": 9257,
"s": 9165,
"text": "Raspberry Pi– single board computer uses Python as its principal user-programming language."
},
{
"code": null,
"e": 9311,
"s": 9257,
"text": "Python is now being used Game Development areas also."
},
{
"code": null,
"e": 9317,
"s": 9311,
"text": "Pros:"
},
{
"code": null,
"e": 9352,
"s": 9317,
"text": "Ease of useMulti-paradigm Approach"
},
{
"code": null,
"e": 9364,
"s": 9352,
"text": "Ease of use"
},
{
"code": null,
"e": 9388,
"s": 9364,
"text": "Multi-paradigm Approach"
},
{
"code": null,
"e": 9394,
"s": 9388,
"text": "Cons:"
},
{
"code": null,
"e": 9715,
"s": 9394,
"text": "Slow speed of execution compared to C,C++Absence from mobile computing and browsersFor the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these."
},
{
"code": null,
"e": 9757,
"s": 9715,
"text": "Slow speed of execution compared to C,C++"
},
{
"code": null,
"e": 9800,
"s": 9757,
"text": "Absence from mobile computing and browsers"
},
{
"code": null,
"e": 10038,
"s": 9800,
"text": "For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these."
},
{
"code": null,
"e": 10060,
"s": 10038,
"text": "Industrial Importance"
},
{
"code": null,
"e": 10325,
"s": 10060,
"text": "Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it."
},
{
"code": null,
"e": 10861,
"s": 10325,
"text": "Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management. "
},
{
"code": null,
"e": 11680,
"s": 10861,
"text": "Presence of third-party modules Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) Open source and community development Versatile, Easy to read, learn and writeUser-friendly data structures High-level language Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) Object-oriented language Portable and InteractiveIdeal for prototypes – provide more functionality with less codingHighly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)(IoT)Internet of Things OpportunitiesInterpreted LanguagePortable across Operating systems "
},
{
"code": null,
"e": 11713,
"s": 11680,
"text": "Presence of third-party modules "
},
{
"code": null,
"e": 11807,
"s": 11713,
"text": "Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) "
},
{
"code": null,
"e": 11846,
"s": 11807,
"text": "Open source and community development "
},
{
"code": null,
"e": 11887,
"s": 11846,
"text": "Versatile, Easy to read, learn and write"
},
{
"code": null,
"e": 11918,
"s": 11887,
"text": "User-friendly data structures "
},
{
"code": null,
"e": 11939,
"s": 11918,
"text": "High-level language "
},
{
"code": null,
"e": 12045,
"s": 11939,
"text": "Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) "
},
{
"code": null,
"e": 12071,
"s": 12045,
"text": "Object-oriented language "
},
{
"code": null,
"e": 12096,
"s": 12071,
"text": "Portable and Interactive"
},
{
"code": null,
"e": 12163,
"s": 12096,
"text": "Ideal for prototypes – provide more functionality with less coding"
},
{
"code": null,
"e": 12418,
"s": 12163,
"text": "Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)"
},
{
"code": null,
"e": 12456,
"s": 12418,
"text": "(IoT)Internet of Things Opportunities"
},
{
"code": null,
"e": 12477,
"s": 12456,
"text": "Interpreted Language"
},
{
"code": null,
"e": 12512,
"s": 12477,
"text": "Portable across Operating systems "
},
{
"code": null,
"e": 12809,
"s": 12514,
"text": "GUI based desktop applicationsGraphic design, image processing applications, Games, and Scientific/ computational ApplicationsWeb frameworks and applications Enterprise and Business applications Operating Systems EducationDatabase AccessLanguage Development Prototyping Software Development "
},
{
"code": null,
"e": 12840,
"s": 12809,
"text": "GUI based desktop applications"
},
{
"code": null,
"e": 12937,
"s": 12840,
"text": "Graphic design, image processing applications, Games, and Scientific/ computational Applications"
},
{
"code": null,
"e": 12970,
"s": 12937,
"text": "Web frameworks and applications "
},
{
"code": null,
"e": 13009,
"s": 12970,
"text": " Enterprise and Business applications "
},
{
"code": null,
"e": 13029,
"s": 13009,
"text": " Operating Systems "
},
{
"code": null,
"e": 13039,
"s": 13029,
"text": "Education"
},
{
"code": null,
"e": 13055,
"s": 13039,
"text": "Database Access"
},
{
"code": null,
"e": 13077,
"s": 13055,
"text": "Language Development "
},
{
"code": null,
"e": 13091,
"s": 13077,
"text": " Prototyping "
},
{
"code": null,
"e": 13113,
"s": 13091,
"text": "Software Development "
},
{
"code": null,
"e": 13143,
"s": 13113,
"text": "Organizations using Python : "
},
{
"code": null,
"e": 13265,
"s": 13143,
"text": "Google(Components of Google spider and Search Engine) Yahoo(Maps) YouTube Mozilla Dropbox Microsoft Cisco Spotify Quora "
},
{
"code": null,
"e": 13320,
"s": 13265,
"text": "Google(Components of Google spider and Search Engine) "
},
{
"code": null,
"e": 13333,
"s": 13320,
"text": "Yahoo(Maps) "
},
{
"code": null,
"e": 13342,
"s": 13333,
"text": "YouTube "
},
{
"code": null,
"e": 13351,
"s": 13342,
"text": "Mozilla "
},
{
"code": null,
"e": 13360,
"s": 13351,
"text": "Dropbox "
},
{
"code": null,
"e": 13371,
"s": 13360,
"text": "Microsoft "
},
{
"code": null,
"e": 13378,
"s": 13371,
"text": "Cisco "
},
{
"code": null,
"e": 13387,
"s": 13378,
"text": "Spotify "
},
{
"code": null,
"e": 13395,
"s": 13387,
"text": "Quora "
},
{
"code": null,
"e": 13609,
"s": 13397,
"text": "So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, Java ( I have taken these 3 because they are most famous and mostly used languages)."
},
{
"code": "# Python code for \"Hello World\"# nothing else to type...see how simple is the syntax. print(\"Hello World\") ",
"e": 13723,
"s": 13609,
"text": null
},
{
"code": null,
"e": 14038,
"s": 13723,
"text": "Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope.Now moving on further Lets start our basics of Python . I will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily."
},
{
"code": null,
"e": 14061,
"s": 14038,
"text": "Introduction and Setup"
},
{
"code": null,
"e": 19614,
"s": 14061,
"text": "If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :The ” >>> ” represents the python shell and its ready to take python commands and code.Variables and Data StructuresIn other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.# Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber =\"helloworld\"print(myNumber)Output:3\n4.5\nhelloworld\nSee, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list.# Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append(\"String\") print(nums)Output:[21, 40.5, String]Comments:# is used for single line comment in Python\n\"\"\" this is a comment \"\"\" is used for multi line commentsInput and OutputIn this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.# Python program to illustrate# getting input from username = input(\"Enter your name: \") # user entered the name 'harssh'print(\"hello\", name)Output:hello harssh # Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input(\"Enter num1: \"))num2 = int(input(\"Enter num2: \")) num3 = num1 * num2print(\"Product is: \", num3)Output:Enter num1: 8 Enter num2: 6 ('Product is: ', 48)\nSelectionSelection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)# Python program to illustrate# selection statement num1 = 34if(num1>12): print(\"Num1 is good\")elif(num1>35): print(\"Num2 is not gooooo....\")else: print(\"Num2 is great\")Output:Num1 is goodFunctionsYou can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:def function-name(arguments):\n #function body# Python program to illustrate# functionsdef hello(): print(\"hello\") print(\"hello again\")hello() # calling functionhello() Output:hello\nhello again\nhello\nhello again\nNow as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages.# Python program to illustrate # function with maindef getInteger(): result = int(input(\"Enter integer: \")) return result def Main(): print(\"Started\") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__==\"__main__\": Main()Output:Started\nEnter integer: 5\nIteration (Looping)As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.# Python program to illustrate# a simple for loop for step in range(5): print(step)Output:0\n1\n2\n3\n4\nModulesPython has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.# Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__==\"__main__\": Main()Output:85.0Related CoursesPython Programming Foundation -Self Paced CourseNew to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today.DS Using Python Programming – Self Paced CourseIf you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 19831,
"s": 19614,
"text": "If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :"
},
{
"code": null,
"e": 19859,
"s": 19831,
"text": "It will look somehow this :"
},
{
"code": null,
"e": 20051,
"s": 19859,
"text": "If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :"
},
{
"code": null,
"e": 20139,
"s": 20051,
"text": "The ” >>> ” represents the python shell and its ready to take python commands and code."
},
{
"code": null,
"e": 20169,
"s": 20139,
"text": "Variables and Data Structures"
},
{
"code": null,
"e": 20480,
"s": 20169,
"text": "In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String."
},
{
"code": "# Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber =\"helloworld\"print(myNumber)",
"e": 20617,
"s": 20480,
"text": null
},
{
"code": null,
"e": 20625,
"s": 20617,
"text": "Output:"
},
{
"code": null,
"e": 20643,
"s": 20625,
"text": "3\n4.5\nhelloworld\n"
},
{
"code": null,
"e": 20855,
"s": 20643,
"text": "See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set."
},
{
"code": null,
"e": 21189,
"s": 20855,
"text": "List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list."
},
{
"code": "# Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append(\"String\") print(nums)",
"e": 21354,
"s": 21189,
"text": null
},
{
"code": null,
"e": 21362,
"s": 21354,
"text": "Output:"
},
{
"code": null,
"e": 21381,
"s": 21362,
"text": "[21, 40.5, String]"
},
{
"code": null,
"e": 21391,
"s": 21381,
"text": "Comments:"
},
{
"code": null,
"e": 21493,
"s": 21391,
"text": "# is used for single line comment in Python\n\"\"\" this is a comment \"\"\" is used for multi line comments"
},
{
"code": null,
"e": 21510,
"s": 21493,
"text": "Input and Output"
},
{
"code": null,
"e": 21673,
"s": 21510,
"text": "In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user."
},
{
"code": "# Python program to illustrate# getting input from username = input(\"Enter your name: \") # user entered the name 'harssh'print(\"hello\", name)",
"e": 21817,
"s": 21673,
"text": null
},
{
"code": null,
"e": 21825,
"s": 21817,
"text": "Output:"
},
{
"code": null,
"e": 21841,
"s": 21825,
"text": "hello harssh "
},
{
"code": "# Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input(\"Enter num1: \"))num2 = int(input(\"Enter num2: \")) num3 = num1 * num2print(\"Product is: \", num3)",
"e": 22123,
"s": 21841,
"text": null
},
{
"code": null,
"e": 22131,
"s": 22123,
"text": "Output:"
},
{
"code": null,
"e": 22181,
"s": 22131,
"text": "Enter num1: 8 Enter num2: 6 ('Product is: ', 48)\n"
},
{
"code": null,
"e": 22191,
"s": 22181,
"text": "Selection"
},
{
"code": null,
"e": 22276,
"s": 22191,
"text": "Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)"
},
{
"code": "# Python program to illustrate# selection statement num1 = 34if(num1>12): print(\"Num1 is good\")elif(num1>35): print(\"Num2 is not gooooo....\")else: print(\"Num2 is great\")",
"e": 22456,
"s": 22276,
"text": null
},
{
"code": null,
"e": 22464,
"s": 22456,
"text": "Output:"
},
{
"code": null,
"e": 22477,
"s": 22464,
"text": "Num1 is good"
},
{
"code": null,
"e": 22487,
"s": 22477,
"text": "Functions"
},
{
"code": null,
"e": 22663,
"s": 22487,
"text": "You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:"
},
{
"code": null,
"e": 22720,
"s": 22663,
"text": "def function-name(arguments):\n #function body"
},
{
"code": "# Python program to illustrate# functionsdef hello(): print(\"hello\") print(\"hello again\")hello() # calling functionhello() ",
"e": 22865,
"s": 22720,
"text": null
},
{
"code": null,
"e": 22873,
"s": 22865,
"text": "Output:"
},
{
"code": null,
"e": 22910,
"s": 22873,
"text": "hello\nhello again\nhello\nhello again\n"
},
{
"code": null,
"e": 23039,
"s": 22910,
"text": "Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages."
},
{
"code": "# Python program to illustrate # function with maindef getInteger(): result = int(input(\"Enter integer: \")) return result def Main(): print(\"Started\") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__==\"__main__\": Main()",
"e": 23450,
"s": 23039,
"text": null
},
{
"code": null,
"e": 23458,
"s": 23450,
"text": "Output:"
},
{
"code": null,
"e": 23484,
"s": 23458,
"text": "Started\nEnter integer: 5\n"
},
{
"code": null,
"e": 23504,
"s": 23484,
"text": "Iteration (Looping)"
},
{
"code": null,
"e": 23614,
"s": 23504,
"text": "As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here."
},
{
"code": "# Python program to illustrate# a simple for loop for step in range(5): print(step)",
"e": 23706,
"s": 23614,
"text": null
},
{
"code": null,
"e": 23714,
"s": 23706,
"text": "Output:"
},
{
"code": null,
"e": 23725,
"s": 23714,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 23733,
"s": 23725,
"text": "Modules"
},
{
"code": null,
"e": 24005,
"s": 23733,
"text": "Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program."
},
{
"code": "# Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__==\"__main__\": Main()",
"e": 24236,
"s": 24005,
"text": null
},
{
"code": null,
"e": 24244,
"s": 24236,
"text": "Output:"
},
{
"code": null,
"e": 24249,
"s": 24244,
"text": "85.0"
},
{
"code": null,
"e": 24684,
"s": 24249,
"text": "New to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today."
},
{
"code": null,
"e": 25099,
"s": 24684,
"text": "If you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today."
},
{
"code": null,
"e": 25114,
"s": 25099,
"text": "shivamsaraswat"
},
{
"code": null,
"e": 25129,
"s": 25114,
"text": "lalitshankarch"
},
{
"code": null,
"e": 25148,
"s": 25129,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 25155,
"s": 25148,
"text": "Python"
},
{
"code": null,
"e": 25174,
"s": 25155,
"text": "School Programming"
},
{
"code": null,
"e": 25272,
"s": 25174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25300,
"s": 25272,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 25350,
"s": 25300,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 25372,
"s": 25350,
"text": "Python map() function"
},
{
"code": null,
"e": 25416,
"s": 25372,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 25458,
"s": 25416,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25483,
"s": 25458,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 25499,
"s": 25483,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 25518,
"s": 25499,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25537,
"s": 25518,
"text": "Inheritance in C++"
}
]
|
Find the minimum dominating set of a Binary tree | 09 Oct, 2021
Given a binary tree with N nodes numbered [1, N], the task is to find the size of the smallest Dominating set of that tree.
A set of nodes is said to be a dominating node if every node in the binary tree not present in the set is an immediate child/parent to any node in that set.
Examples:
Input:
1
/
2
/ \
4 3
/
5
/ \
6 7
/ \ \
8 9 10
Output: 3
Explanation:
Smallest dominating set is {2, 6, 7}
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /
8 9 10
Output: 4
Explanation:
One of the smallest
dominating set = {2, 3, 6, 4}
Approach: In order to solve this problem we are using a dynamic programming approach by defining the following two states for every node:
The first state compulsory tells us whether it is compulsory to choose the node in the set or not.
The second state covered, tells us whether the node’s parent/child is in the set or not.
If it is compulsory to choose the node, we choose it and mark its children as covered. Otherwise, we have an option to choose it or reject it and then update its children as covered or not accordingly. Check the states for every node and find the required size of the set accordingly.Below code is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
/* C++ program to find the size of theminimum dominating set of the tree */ #include <bits/stdc++.h>using namespace std; #define N 1005 // Definition of a tree nodestruct Node { int data; Node *left, *right;}; /* Helper function that allocates anew node */Node* newNode(int data){ Node* node = new Node(); node->data = data; node->left = node->right = NULL; return node;} // DP array to precompute// and store the resultsint dp[N][5][5]; // minDominatingSettion to return the size of// the minimum dominating set of the arrayint minDominatingSet(Node* root, int covered, int compulsory){ // Base case if (!root) return 0; // Setting the compulsory value if needed if (!root->left and !root->right and !covered) compulsory = true; // Check if the answer is already computed if (dp[root->data][covered][compulsory] != -1) return dp[root->data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory) { // Choose the node and set its children as covered return dp[root->data] [covered] [compulsory] = 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0); } // If it is covered if (covered) { return dp[root->data] [covered] [compulsory] = min( 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0), minDominatingSet( root->left, 0, 0) + minDominatingSet( root->right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0); if (root->left) { ans = min(ans, minDominatingSet( root->left, 0, 1) + minDominatingSet( root->right, 0, 0)); } if (root->right) { ans = min(ans, minDominatingSet( root->left, 0, 0) + minDominatingSet( root->right, 0, 1)); } // Store the result return dp[root->data] [covered] [compulsory] = ans;} // Driver codesigned main(){ // initialising the DP array memset(dp, -1, sizeof(dp)); // Constructing the tree Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->left->left->left = newNode(5); root->left->left->left->left = newNode(6); root->left->left->left->right = newNode(7); root->left->left->left->right->right = newNode(10); root->left->left->left->left->left = newNode(8); root->left->left->left->left->right = newNode(9); cout << minDominatingSet(root, 0, 0) << endl; return 0;}
// Java program to find the size of the//minimum dominating set of the treeimport java.util.*; class GFG{ static final int N = 1005; // Definition of a tree nodestatic class Node{ int data; Node left, right;}; // Helper function that allocates a// new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return node;} // DP array to precompute// and store the resultsstatic int [][][]dp = new int[N][5][5]; // minDominatingSettion to return the size of// the minimum dominating set of the arraystatic int minDominatingSet(Node root, int covered, int compulsory){ // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1) return dp[root.data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data][covered] [compulsory] = Math.min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result return dp[root.data][covered][compulsory] = ans;} // Driver codepublic static void main(String[] args){ // Initialising the DP array for(int i = 0; i < N; i++) { for(int j = 0; j < 5; j++) { for(int l = 0; l < 5; l++) dp[i][j][l] = -1; } } // Constructing the tree Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); System.out.print(minDominatingSet( root, 0, 0) + "\n");}} // This code is contributed by amal kumar choubey
# Python3 program to find the size of the# minimum dominating set of the tree */N = 1005 # Definition of a tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a# new nodedef newNode(data): node = Node(data) return node # DP array to precompute# and store the resultsdp = [[[-1 for i in range(5)] for j in range(5)] for k in range(N)]; # minDominatingSettion to return the size of# the minimum dominating set of the arraydef minDominatingSet(root, covered, compulsory): # Base case if (not root): return 0; # Setting the compulsory value if needed if (not root.left and not root.right and not covered): compulsory = True; # Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1): return dp[root.data][covered][compulsory]; # If it is compulsory to select # the node if (compulsory): dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); # Choose the node and set its children as covered return dp[root.data][covered][compulsory] # If it is covered if (covered): dp[root.data][covered][compulsory] = min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0),minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); return dp[root.data][covered][compulsory] # If the current node is neither covered nor # needs to be selected compulsorily ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left): ans = min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); if (root.right): ans = min(ans, minDominatingSet( root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); # Store the result dp[root.data][covered][compulsory]= ans; return ans # Driver codeif __name__=='__main__': # Constructing the tree root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); print(minDominatingSet(root, 0, 0)) # This code is contributed by rutvik_56
// C# program to find the size of the//minimum dominating set of the treeusing System;class GFG{ static readonly int N = 1005; // Definition of a tree nodepublic class Node{ public int data; public Node left, right;}; // Helper function that allocates a// new nodepublic static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return node;} // DP array to precompute// and store the resultsstatic int [,,]dp = new int[N, 5, 5]; // minDominatingSettion to return the size of// the minimum dominating set of the arraystatic int minDominatingSet(Node root, int covered, int compulsory){ // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data, covered, compulsory] != -1) return dp[root.data, covered, compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data, covered, compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data, covered, compulsory] = Math.Min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.Min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.Min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result return dp[root.data, covered, compulsory] = ans;} // Driver codepublic static void Main(String[] args){ // Initialising the DP array for(int i = 0; i < N; i++) { for(int j = 0; j < 5; j++) { for(int l = 0; l < 5; l++) dp[i, j, l] = -1; } } // Constructing the tree Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); Console.Write(minDominatingSet root, 0, 0) + "\n");}} // This code is contributed by Rohit_ranjan
<script> // JavaScript program to find the size of the //minimum dominating set of the tree let N = 1005; // Definition of a tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Helper function that allocates a // new node function newNode(data) { let node = new Node(data); return node; } // DP array to precompute // and store the results let dp = new Array(N); // minDominatingSettion to return the size of // the minimum dominating set of the array function minDominatingSet(root, covered, compulsory) { // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1) return dp[root.data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data][covered] [compulsory] = Math.min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily let ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result dp[root.data][covered][compulsory] = ans; return dp[root.data][covered][compulsory]; } // Initialising the DP array for(let i = 0; i < N; i++) { dp[i] = new Array(5); for(let j = 0; j < 5; j++) { dp[i][j] = new Array(5); for(let l = 0; l < 5; l++) dp[i][j][l] = -1; } } // Constructing the tree let root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); document.write(minDominatingSet(root, 0, 0)); </script>
3
Time Complexity: O(N) Auxiliary Space: O(N)
Amal Kumar Choubey
Rohit_ranjan
rutvik_56
rameshtravel07
pankajsharmagfg
ashutoshsinghgeeksforgeeks
Competitive Programming
Data Structures
Dynamic Programming
Recursion
Tree
Data Structures
Dynamic Programming
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Oct, 2021"
},
{
"code": null,
"e": 176,
"s": 52,
"text": "Given a binary tree with N nodes numbered [1, N], the task is to find the size of the smallest Dominating set of that tree."
},
{
"code": null,
"e": 333,
"s": 176,
"text": "A set of nodes is said to be a dominating node if every node in the binary tree not present in the set is an immediate child/parent to any node in that set."
},
{
"code": null,
"e": 343,
"s": 333,
"text": "Examples:"
},
{
"code": null,
"e": 890,
"s": 343,
"text": "Input: \n 1\n /\n 2\n / \\\n 4 3\n /\n 5\n / \\\n 6 7\n / \\ \\\n 8 9 10\nOutput: 3\nExplanation: \nSmallest dominating set is {2, 6, 7}\n\nInput: \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ /\n 8 9 10\nOutput: 4\nExplanation: \nOne of the smallest\ndominating set = {2, 3, 6, 4}"
},
{
"code": null,
"e": 1028,
"s": 890,
"text": "Approach: In order to solve this problem we are using a dynamic programming approach by defining the following two states for every node:"
},
{
"code": null,
"e": 1127,
"s": 1028,
"text": "The first state compulsory tells us whether it is compulsory to choose the node in the set or not."
},
{
"code": null,
"e": 1216,
"s": 1127,
"text": "The second state covered, tells us whether the node’s parent/child is in the set or not."
},
{
"code": null,
"e": 1556,
"s": 1216,
"text": "If it is compulsory to choose the node, we choose it and mark its children as covered. Otherwise, we have an option to choose it or reject it and then update its children as covered or not accordingly. Check the states for every node and find the required size of the set accordingly.Below code is the implementation of the above approach:"
},
{
"code": null,
"e": 1560,
"s": 1556,
"text": "C++"
},
{
"code": null,
"e": 1565,
"s": 1560,
"text": "Java"
},
{
"code": null,
"e": 1573,
"s": 1565,
"text": "Python3"
},
{
"code": null,
"e": 1576,
"s": 1573,
"text": "C#"
},
{
"code": null,
"e": 1587,
"s": 1576,
"text": "Javascript"
},
{
"code": "/* C++ program to find the size of theminimum dominating set of the tree */ #include <bits/stdc++.h>using namespace std; #define N 1005 // Definition of a tree nodestruct Node { int data; Node *left, *right;}; /* Helper function that allocates anew node */Node* newNode(int data){ Node* node = new Node(); node->data = data; node->left = node->right = NULL; return node;} // DP array to precompute// and store the resultsint dp[N][5][5]; // minDominatingSettion to return the size of// the minimum dominating set of the arrayint minDominatingSet(Node* root, int covered, int compulsory){ // Base case if (!root) return 0; // Setting the compulsory value if needed if (!root->left and !root->right and !covered) compulsory = true; // Check if the answer is already computed if (dp[root->data][covered][compulsory] != -1) return dp[root->data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory) { // Choose the node and set its children as covered return dp[root->data] [covered] [compulsory] = 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0); } // If it is covered if (covered) { return dp[root->data] [covered] [compulsory] = min( 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0), minDominatingSet( root->left, 0, 0) + minDominatingSet( root->right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet( root->left, 1, 0) + minDominatingSet( root->right, 1, 0); if (root->left) { ans = min(ans, minDominatingSet( root->left, 0, 1) + minDominatingSet( root->right, 0, 0)); } if (root->right) { ans = min(ans, minDominatingSet( root->left, 0, 0) + minDominatingSet( root->right, 0, 1)); } // Store the result return dp[root->data] [covered] [compulsory] = ans;} // Driver codesigned main(){ // initialising the DP array memset(dp, -1, sizeof(dp)); // Constructing the tree Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->left->left->left = newNode(5); root->left->left->left->left = newNode(6); root->left->left->left->right = newNode(7); root->left->left->left->right->right = newNode(10); root->left->left->left->left->left = newNode(8); root->left->left->left->left->right = newNode(9); cout << minDominatingSet(root, 0, 0) << endl; return 0;}",
"e": 4828,
"s": 1587,
"text": null
},
{
"code": "// Java program to find the size of the//minimum dominating set of the treeimport java.util.*; class GFG{ static final int N = 1005; // Definition of a tree nodestatic class Node{ int data; Node left, right;}; // Helper function that allocates a// new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return node;} // DP array to precompute// and store the resultsstatic int [][][]dp = new int[N][5][5]; // minDominatingSettion to return the size of// the minimum dominating set of the arraystatic int minDominatingSet(Node root, int covered, int compulsory){ // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1) return dp[root.data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data][covered] [compulsory] = Math.min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result return dp[root.data][covered][compulsory] = ans;} // Driver codepublic static void main(String[] args){ // Initialising the DP array for(int i = 0; i < N; i++) { for(int j = 0; j < 5; j++) { for(int l = 0; l < 5; l++) dp[i][j][l] = -1; } } // Constructing the tree Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); System.out.print(minDominatingSet( root, 0, 0) + \"\\n\");}} // This code is contributed by amal kumar choubey",
"e": 7922,
"s": 4828,
"text": null
},
{
"code": "# Python3 program to find the size of the# minimum dominating set of the tree */N = 1005 # Definition of a tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates a# new nodedef newNode(data): node = Node(data) return node # DP array to precompute# and store the resultsdp = [[[-1 for i in range(5)] for j in range(5)] for k in range(N)]; # minDominatingSettion to return the size of# the minimum dominating set of the arraydef minDominatingSet(root, covered, compulsory): # Base case if (not root): return 0; # Setting the compulsory value if needed if (not root.left and not root.right and not covered): compulsory = True; # Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1): return dp[root.data][covered][compulsory]; # If it is compulsory to select # the node if (compulsory): dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); # Choose the node and set its children as covered return dp[root.data][covered][compulsory] # If it is covered if (covered): dp[root.data][covered][compulsory] = min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0),minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); return dp[root.data][covered][compulsory] # If the current node is neither covered nor # needs to be selected compulsorily ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left): ans = min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); if (root.right): ans = min(ans, minDominatingSet( root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); # Store the result dp[root.data][covered][compulsory]= ans; return ans # Driver codeif __name__=='__main__': # Constructing the tree root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); print(minDominatingSet(root, 0, 0)) # This code is contributed by rutvik_56",
"e": 10494,
"s": 7922,
"text": null
},
{
"code": "// C# program to find the size of the//minimum dominating set of the treeusing System;class GFG{ static readonly int N = 1005; // Definition of a tree nodepublic class Node{ public int data; public Node left, right;}; // Helper function that allocates a// new nodepublic static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return node;} // DP array to precompute// and store the resultsstatic int [,,]dp = new int[N, 5, 5]; // minDominatingSettion to return the size of// the minimum dominating set of the arraystatic int minDominatingSet(Node root, int covered, int compulsory){ // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data, covered, compulsory] != -1) return dp[root.data, covered, compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data, covered, compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data, covered, compulsory] = Math.Min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily int ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.Min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.Min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result return dp[root.data, covered, compulsory] = ans;} // Driver codepublic static void Main(String[] args){ // Initialising the DP array for(int i = 0; i < N; i++) { for(int j = 0; j < 5; j++) { for(int l = 0; l < 5; l++) dp[i, j, l] = -1; } } // Constructing the tree Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); Console.Write(minDominatingSet root, 0, 0) + \"\\n\");}} // This code is contributed by Rohit_ranjan",
"e": 13632,
"s": 10494,
"text": null
},
{
"code": "<script> // JavaScript program to find the size of the //minimum dominating set of the tree let N = 1005; // Definition of a tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Helper function that allocates a // new node function newNode(data) { let node = new Node(data); return node; } // DP array to precompute // and store the results let dp = new Array(N); // minDominatingSettion to return the size of // the minimum dominating set of the array function minDominatingSet(root, covered, compulsory) { // Base case if (root == null) return 0; // Setting the compulsory value if needed if (root.left != null && root.right != null && covered > 0) compulsory = 1; // Check if the answer is already computed if (dp[root.data][covered][compulsory] != -1) return dp[root.data][covered][compulsory]; // If it is compulsory to select // the node if (compulsory > 0) { // Choose the node and set its // children as covered return dp[root.data][covered][compulsory] = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); } // If it is covered if (covered > 0) { return dp[root.data][covered] [compulsory] = Math.min(1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0), minDominatingSet(root.left, 0, 0)+ minDominatingSet(root.right, 0, 0)); } // If the current node is neither covered nor // needs to be selected compulsorily let ans = 1 + minDominatingSet(root.left, 1, 0) + minDominatingSet(root.right, 1, 0); if (root.left != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 1) + minDominatingSet(root.right, 0, 0)); } if (root.right != null) { ans = Math.min(ans, minDominatingSet(root.left, 0, 0) + minDominatingSet(root.right, 0, 1)); } // Store the result dp[root.data][covered][compulsory] = ans; return dp[root.data][covered][compulsory]; } // Initialising the DP array for(let i = 0; i < N; i++) { dp[i] = new Array(5); for(let j = 0; j < 5; j++) { dp[i][j] = new Array(5); for(let l = 0; l < 5; l++) dp[i][j][l] = -1; } } // Constructing the tree let root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); root.left.right = newNode(4); root.left.left.left = newNode(5); root.left.left.left.left = newNode(6); root.left.left.left.right = newNode(7); root.left.left.left.right.right = newNode(10); root.left.left.left.left.left = newNode(8); root.left.left.left.left.right = newNode(9); document.write(minDominatingSet(root, 0, 0)); </script>",
"e": 16920,
"s": 13632,
"text": null
},
{
"code": null,
"e": 16922,
"s": 16920,
"text": "3"
},
{
"code": null,
"e": 16969,
"s": 16924,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 16988,
"s": 16969,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 17001,
"s": 16988,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 17011,
"s": 17001,
"text": "rutvik_56"
},
{
"code": null,
"e": 17026,
"s": 17011,
"text": "rameshtravel07"
},
{
"code": null,
"e": 17042,
"s": 17026,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 17069,
"s": 17042,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 17093,
"s": 17069,
"text": "Competitive Programming"
},
{
"code": null,
"e": 17109,
"s": 17093,
"text": "Data Structures"
},
{
"code": null,
"e": 17129,
"s": 17109,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 17139,
"s": 17129,
"text": "Recursion"
},
{
"code": null,
"e": 17144,
"s": 17139,
"text": "Tree"
},
{
"code": null,
"e": 17160,
"s": 17144,
"text": "Data Structures"
},
{
"code": null,
"e": 17180,
"s": 17160,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 17190,
"s": 17180,
"text": "Recursion"
},
{
"code": null,
"e": 17195,
"s": 17190,
"text": "Tree"
}
]
|
Early Design Model : COCOMO-II | 28 Sep, 2020
It is used at the Stage – II in COCOMO -II models and supports estimation in early design stage of project. Base equation used in COCOMO – II models is as follows –
PMnominal = A * (size)B
where PMnominal = Effort for the project in person months
A = constant representing the nominal productivity where A = 2.5
B = Scale Factor
Size = size of the Software
The early design model uses Unadjusted Function Points (UFP) as measure of size. This model is used at the early stages of software project when there is not enough information available about size of product which has t be developed, nature of target platform and nature of employees to be involved in development of projector detailed specifications of process to be used. This model can be used in either Application Generator, System Integration, or Infrastructure Development Sector.
If B = 1.0, there is linear relationship between effort and size of product. If the value of B is not equal to 1, there will be non-linear relationship between size of product and effort. If B < 1.0, rate of increase of effort decreases as the size of product increases. If B > 1.0, rate of increase of effort increase as the size of product is increased.
This is due to growth of interpersonal communications and overheads due to growth of large system integration. Application composition model assumes value of B equal to 1. But Early Design Model assumes value of B to be greater than 1.
Thus here the basic assumption stands as effort on project usually increases faster than size of product. However, value of ‘B’ is computed on basis of scaling factors that may cause loss of productivity corresponding to an increase in the size as follows –
Precedentness :It reflects the experience on similar projects previously. This is applicable to individuals as well as organizations both in terms of expertise and experience. High value would imply that organization is quite familiar with application formula and very low value means no previous experience or expertise. The value for scale factor is 6.20(Very Low), 4.96(Low), 3.72(Average), 2.48(High), 1.25(Very High) and 0.00(Extra High).Development Flexibility :It reflects degree of flexibility in development process. Low value would imply well defined process being used. Very high value would imply that the client offers very general idea of the product or project. Value for the scale factor is 5.07(Very Low), 4.05(Low), 3.04(Average), 2.03(High), 1.02(Very High) and 0.00(Extra High).Architecture Risk and Resolution :It represents degree of risk analysis being carried out during course of project. Low value would indicate little analysis and very high value would represent complete and thorough risk analysis. Value for the scale factor is 7.07(Very Low), 5.65(Low), 4.24(Average), 2.83(High), 1.41(Very High) and 0.00(Extra High).Team Cohesion :Reflects the team management skills of the employees developing the project. Very low value would imply very low interaction and hardly any relationship among the members however high value would imply great relationship and good team work. The value for scale factor is 5.48(Very Low), 4.38(Low), 3.29(Average), 2.19(High), 1.10(Very High) and 0.00(Extra High).Process maturity :Reflects process maturity of organization. Very low value would imply organization has no level at all and high value would imply that organization is rated as highest level of the SEI-CMM. The value for scale factor is 7.80(Very Low), 6.24(Low), 4.68(Average), 3.12(High), 1.56(Very High) and 0.00(Extra High).
Precedentness :It reflects the experience on similar projects previously. This is applicable to individuals as well as organizations both in terms of expertise and experience. High value would imply that organization is quite familiar with application formula and very low value means no previous experience or expertise. The value for scale factor is 6.20(Very Low), 4.96(Low), 3.72(Average), 2.48(High), 1.25(Very High) and 0.00(Extra High).
Development Flexibility :It reflects degree of flexibility in development process. Low value would imply well defined process being used. Very high value would imply that the client offers very general idea of the product or project. Value for the scale factor is 5.07(Very Low), 4.05(Low), 3.04(Average), 2.03(High), 1.02(Very High) and 0.00(Extra High).
Architecture Risk and Resolution :It represents degree of risk analysis being carried out during course of project. Low value would indicate little analysis and very high value would represent complete and thorough risk analysis. Value for the scale factor is 7.07(Very Low), 5.65(Low), 4.24(Average), 2.83(High), 1.41(Very High) and 0.00(Extra High).
Team Cohesion :Reflects the team management skills of the employees developing the project. Very low value would imply very low interaction and hardly any relationship among the members however high value would imply great relationship and good team work. The value for scale factor is 5.48(Very Low), 4.38(Low), 3.29(Average), 2.19(High), 1.10(Very High) and 0.00(Extra High).
Process maturity :Reflects process maturity of organization. Very low value would imply organization has no level at all and high value would imply that organization is rated as highest level of the SEI-CMM. The value for scale factor is 7.80(Very Low), 6.24(Low), 4.68(Average), 3.12(High), 1.56(Very High) and 0.00(Extra High).
The value of B can be calculated as -
B = 0.91 + 0.01 * (Sum of rating scaling factors for project)
When all scaling factors of project are rated as extra high, best value of B is obtained which is equal to 0.91.
When all scaling factors are very low worst case values of B is obtained as 1.23.
Hence value of B varies from 0.91 to 1.23.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Sep, 2020"
},
{
"code": null,
"e": 193,
"s": 28,
"text": "It is used at the Stage – II in COCOMO -II models and supports estimation in early design stage of project. Base equation used in COCOMO – II models is as follows –"
},
{
"code": null,
"e": 387,
"s": 193,
"text": "PMnominal = A * (size)B \nwhere PMnominal = Effort for the project in person months\nA = constant representing the nominal productivity where A = 2.5\nB = Scale Factor\nSize = size of the Software\n"
},
{
"code": null,
"e": 876,
"s": 387,
"text": "The early design model uses Unadjusted Function Points (UFP) as measure of size. This model is used at the early stages of software project when there is not enough information available about size of product which has t be developed, nature of target platform and nature of employees to be involved in development of projector detailed specifications of process to be used. This model can be used in either Application Generator, System Integration, or Infrastructure Development Sector."
},
{
"code": null,
"e": 1232,
"s": 876,
"text": "If B = 1.0, there is linear relationship between effort and size of product. If the value of B is not equal to 1, there will be non-linear relationship between size of product and effort. If B < 1.0, rate of increase of effort decreases as the size of product increases. If B > 1.0, rate of increase of effort increase as the size of product is increased."
},
{
"code": null,
"e": 1468,
"s": 1232,
"text": "This is due to growth of interpersonal communications and overheads due to growth of large system integration. Application composition model assumes value of B equal to 1. But Early Design Model assumes value of B to be greater than 1."
},
{
"code": null,
"e": 1726,
"s": 1468,
"text": "Thus here the basic assumption stands as effort on project usually increases faster than size of product. However, value of ‘B’ is computed on basis of scaling factors that may cause loss of productivity corresponding to an increase in the size as follows –"
},
{
"code": null,
"e": 3582,
"s": 1726,
"text": "Precedentness :It reflects the experience on similar projects previously. This is applicable to individuals as well as organizations both in terms of expertise and experience. High value would imply that organization is quite familiar with application formula and very low value means no previous experience or expertise. The value for scale factor is 6.20(Very Low), 4.96(Low), 3.72(Average), 2.48(High), 1.25(Very High) and 0.00(Extra High).Development Flexibility :It reflects degree of flexibility in development process. Low value would imply well defined process being used. Very high value would imply that the client offers very general idea of the product or project. Value for the scale factor is 5.07(Very Low), 4.05(Low), 3.04(Average), 2.03(High), 1.02(Very High) and 0.00(Extra High).Architecture Risk and Resolution :It represents degree of risk analysis being carried out during course of project. Low value would indicate little analysis and very high value would represent complete and thorough risk analysis. Value for the scale factor is 7.07(Very Low), 5.65(Low), 4.24(Average), 2.83(High), 1.41(Very High) and 0.00(Extra High).Team Cohesion :Reflects the team management skills of the employees developing the project. Very low value would imply very low interaction and hardly any relationship among the members however high value would imply great relationship and good team work. The value for scale factor is 5.48(Very Low), 4.38(Low), 3.29(Average), 2.19(High), 1.10(Very High) and 0.00(Extra High).Process maturity :Reflects process maturity of organization. Very low value would imply organization has no level at all and high value would imply that organization is rated as highest level of the SEI-CMM. The value for scale factor is 7.80(Very Low), 6.24(Low), 4.68(Average), 3.12(High), 1.56(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 4026,
"s": 3582,
"text": "Precedentness :It reflects the experience on similar projects previously. This is applicable to individuals as well as organizations both in terms of expertise and experience. High value would imply that organization is quite familiar with application formula and very low value means no previous experience or expertise. The value for scale factor is 6.20(Very Low), 4.96(Low), 3.72(Average), 2.48(High), 1.25(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 4382,
"s": 4026,
"text": "Development Flexibility :It reflects degree of flexibility in development process. Low value would imply well defined process being used. Very high value would imply that the client offers very general idea of the product or project. Value for the scale factor is 5.07(Very Low), 4.05(Low), 3.04(Average), 2.03(High), 1.02(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 4734,
"s": 4382,
"text": "Architecture Risk and Resolution :It represents degree of risk analysis being carried out during course of project. Low value would indicate little analysis and very high value would represent complete and thorough risk analysis. Value for the scale factor is 7.07(Very Low), 5.65(Low), 4.24(Average), 2.83(High), 1.41(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 5112,
"s": 4734,
"text": "Team Cohesion :Reflects the team management skills of the employees developing the project. Very low value would imply very low interaction and hardly any relationship among the members however high value would imply great relationship and good team work. The value for scale factor is 5.48(Very Low), 4.38(Low), 3.29(Average), 2.19(High), 1.10(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 5442,
"s": 5112,
"text": "Process maturity :Reflects process maturity of organization. Very low value would imply organization has no level at all and high value would imply that organization is rated as highest level of the SEI-CMM. The value for scale factor is 7.80(Very Low), 6.24(Low), 4.68(Average), 3.12(High), 1.56(Very High) and 0.00(Extra High)."
},
{
"code": null,
"e": 5543,
"s": 5442,
"text": "The value of B can be calculated as -\nB = 0.91 + 0.01 * (Sum of rating scaling factors for project)\n"
},
{
"code": null,
"e": 5656,
"s": 5543,
"text": "When all scaling factors of project are rated as extra high, best value of B is obtained which is equal to 0.91."
},
{
"code": null,
"e": 5738,
"s": 5656,
"text": "When all scaling factors are very low worst case values of B is obtained as 1.23."
},
{
"code": null,
"e": 5781,
"s": 5738,
"text": "Hence value of B varies from 0.91 to 1.23."
},
{
"code": null,
"e": 5802,
"s": 5781,
"text": "Software Engineering"
}
]
|
Java Program to Access All Data as Object Array | 09 Apr, 2022
Java is an object-oriented programming language. Most of the work is done with the help of objects. We know that an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types.
Java allows us to store objects in an array. In Java, the class is also a user-defined data type. An array that contains class-type elements is known as an array of objects.
It stores the reference variable of the object.
This Array is used to implement on data sets that require performing operations on different data types simultaneously same like structures in c, this Objects array provide us the luxury to calculate
For example, if we want to write a program that works with books details typically contain various attributes like book id(integer), name(String), Author name(string),..etc which are of various data types, so we construct an array Object for Book and write the methods that fetch out various details of this book.
Illustration:
Book[] b = new Book[array_length];
Here we created an array with instance b for class Book, now we can simply add attribute values for a book with their data types which can be depicted from the image below
In order to create arrays of objects, the syntax is as follows:
Way 1
ClassName object[]=new ClassName[array_length];
Way 2
ClassName[] objArray;
Way 3
ClassName objectArray[];
Implementation: Array of objects
Suppose, let’s consider we have created a class named Employee. We want to keep records of 20 employees of a company having three departments. In this case, we will not create 20 separate variables. Instead of this, we will create an array of objects:
Employee_department1[20];
Employee_department2[20];
Employee_department3[20];
Example:
Java
// Java Program to Implement Array Of Objects // Class 1// Helper class// Product class- product Id and product name as attributesclass Product { // Member variables // Product ID int pro_Id; // Product name String pro_name; // Constructor Product(int pid, String n) { pro_Id = pid; pro_name = n; } // Method of this class public void display() { // Print and display the productID and product name System.out.print("Product Id = " + pro_Id + " " + " Product Name = " + pro_name); System.out.println(); }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an array of product object, or simply // creating array of object of class 1 Product[] obj = new Product[5]; // Creating & initializing actual product objects // using constructor // Custom input arguments obj[0] = new Product(23907, "Hp Omen Gaming 15"); obj[1] = new Product(91240, "Dell G3 Gaming"); obj[2] = new Product(29823, "Asus TUF Gaming"); obj[3] = new Product(11908, "Lenovo Legion Gaming"); obj[4] = new Product(43590, "Acer Predator Gaming"); // Lastly displaying the product object data System.out.println("Product Object 1:"); obj[0].display(); System.out.println("Product Object 2:"); obj[1].display(); System.out.println("Product Object 3:"); obj[2].display(); System.out.println("Product Object 4:"); obj[3].display(); System.out.println("Product Object 5:"); obj[4].display(); }}
Product Object 1:
Product Id = 23907 Product Name = Hp Omen Gaming 15
Product Object 2:
Product Id = 91240 Product Name = Dell G3 Gaming
Product Object 3:
Product Id = 29823 Product Name = Asus TUF Gaming
Product Object 4:
Product Id = 11908 Product Name = Lenovo Legion Gamig
Product Object 5:
Product Id = 43590 Product Name = Acer Predator Gaming
Output Explanation:
In the following program, we have created a class named Product and initialized an array of objects using the constructor.
We have created a constructor of the class Product that contains the product ID and product name. In the main function, we have created individual objects of the class Product. After that, we have passed initial values to each of the objects using the constructor.
Now, this code displays the Product id and name of various brands of gaming laptops.
This size of the object array in this code was set, but it can be increased based on the requirement.
Similarly, we can create a generalized Array object to run the Business Logic.
gabaa406
gulshankumarar231
xlife425
Java-Array-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Apr, 2022"
},
{
"code": null,
"e": 288,
"s": 53,
"text": "Java is an object-oriented programming language. Most of the work is done with the help of objects. We know that an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types."
},
{
"code": null,
"e": 462,
"s": 288,
"text": "Java allows us to store objects in an array. In Java, the class is also a user-defined data type. An array that contains class-type elements is known as an array of objects."
},
{
"code": null,
"e": 510,
"s": 462,
"text": "It stores the reference variable of the object."
},
{
"code": null,
"e": 710,
"s": 510,
"text": "This Array is used to implement on data sets that require performing operations on different data types simultaneously same like structures in c, this Objects array provide us the luxury to calculate"
},
{
"code": null,
"e": 1024,
"s": 710,
"text": "For example, if we want to write a program that works with books details typically contain various attributes like book id(integer), name(String), Author name(string),..etc which are of various data types, so we construct an array Object for Book and write the methods that fetch out various details of this book."
},
{
"code": null,
"e": 1038,
"s": 1024,
"text": "Illustration:"
},
{
"code": null,
"e": 1073,
"s": 1038,
"text": "Book[] b = new Book[array_length];"
},
{
"code": null,
"e": 1245,
"s": 1073,
"text": "Here we created an array with instance b for class Book, now we can simply add attribute values for a book with their data types which can be depicted from the image below"
},
{
"code": null,
"e": 1309,
"s": 1245,
"text": "In order to create arrays of objects, the syntax is as follows:"
},
{
"code": null,
"e": 1315,
"s": 1309,
"text": "Way 1"
},
{
"code": null,
"e": 1363,
"s": 1315,
"text": "ClassName object[]=new ClassName[array_length];"
},
{
"code": null,
"e": 1369,
"s": 1363,
"text": "Way 2"
},
{
"code": null,
"e": 1392,
"s": 1369,
"text": "ClassName[] objArray; "
},
{
"code": null,
"e": 1398,
"s": 1392,
"text": "Way 3"
},
{
"code": null,
"e": 1425,
"s": 1398,
"text": "ClassName objectArray[]; "
},
{
"code": null,
"e": 1459,
"s": 1425,
"text": "Implementation: Array of objects "
},
{
"code": null,
"e": 1711,
"s": 1459,
"text": "Suppose, let’s consider we have created a class named Employee. We want to keep records of 20 employees of a company having three departments. In this case, we will not create 20 separate variables. Instead of this, we will create an array of objects:"
},
{
"code": null,
"e": 1792,
"s": 1711,
"text": "Employee_department1[20]; \nEmployee_department2[20]; \nEmployee_department3[20];"
},
{
"code": null,
"e": 1801,
"s": 1792,
"text": "Example:"
},
{
"code": null,
"e": 1806,
"s": 1801,
"text": "Java"
},
{
"code": "// Java Program to Implement Array Of Objects // Class 1// Helper class// Product class- product Id and product name as attributesclass Product { // Member variables // Product ID int pro_Id; // Product name String pro_name; // Constructor Product(int pid, String n) { pro_Id = pid; pro_name = n; } // Method of this class public void display() { // Print and display the productID and product name System.out.print(\"Product Id = \" + pro_Id + \" \" + \" Product Name = \" + pro_name); System.out.println(); }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an array of product object, or simply // creating array of object of class 1 Product[] obj = new Product[5]; // Creating & initializing actual product objects // using constructor // Custom input arguments obj[0] = new Product(23907, \"Hp Omen Gaming 15\"); obj[1] = new Product(91240, \"Dell G3 Gaming\"); obj[2] = new Product(29823, \"Asus TUF Gaming\"); obj[3] = new Product(11908, \"Lenovo Legion Gaming\"); obj[4] = new Product(43590, \"Acer Predator Gaming\"); // Lastly displaying the product object data System.out.println(\"Product Object 1:\"); obj[0].display(); System.out.println(\"Product Object 2:\"); obj[1].display(); System.out.println(\"Product Object 3:\"); obj[2].display(); System.out.println(\"Product Object 4:\"); obj[3].display(); System.out.println(\"Product Object 5:\"); obj[4].display(); }}",
"e": 3507,
"s": 1806,
"text": null
},
{
"code": null,
"e": 3867,
"s": 3507,
"text": "Product Object 1:\nProduct Id = 23907 Product Name = Hp Omen Gaming 15\nProduct Object 2:\nProduct Id = 91240 Product Name = Dell G3 Gaming\nProduct Object 3:\nProduct Id = 29823 Product Name = Asus TUF Gaming\nProduct Object 4:\nProduct Id = 11908 Product Name = Lenovo Legion Gamig\nProduct Object 5:\nProduct Id = 43590 Product Name = Acer Predator Gaming"
},
{
"code": null,
"e": 3888,
"s": 3867,
"text": "Output Explanation: "
},
{
"code": null,
"e": 4011,
"s": 3888,
"text": "In the following program, we have created a class named Product and initialized an array of objects using the constructor."
},
{
"code": null,
"e": 4276,
"s": 4011,
"text": "We have created a constructor of the class Product that contains the product ID and product name. In the main function, we have created individual objects of the class Product. After that, we have passed initial values to each of the objects using the constructor."
},
{
"code": null,
"e": 4361,
"s": 4276,
"text": "Now, this code displays the Product id and name of various brands of gaming laptops."
},
{
"code": null,
"e": 4463,
"s": 4361,
"text": "This size of the object array in this code was set, but it can be increased based on the requirement."
},
{
"code": null,
"e": 4542,
"s": 4463,
"text": "Similarly, we can create a generalized Array object to run the Business Logic."
},
{
"code": null,
"e": 4553,
"s": 4544,
"text": "gabaa406"
},
{
"code": null,
"e": 4571,
"s": 4553,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4580,
"s": 4571,
"text": "xlife425"
},
{
"code": null,
"e": 4600,
"s": 4580,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 4607,
"s": 4600,
"text": "Picked"
},
{
"code": null,
"e": 4612,
"s": 4607,
"text": "Java"
},
{
"code": null,
"e": 4626,
"s": 4612,
"text": "Java Programs"
},
{
"code": null,
"e": 4631,
"s": 4626,
"text": "Java"
}
]
|
ML | V-Measure for Evaluating Clustering Performance | 28 Nov, 2019
One of the primary disadvantages of any clustering technique is that it is difficult to evaluate its performance. To tackle this problem, the metric of V-Measure was developed.
The calculation of the V-Measure first requires the calculation of two terms:-
Homogenity: A perfectly homogeneous clustering is one where each cluster has data-points belonging to the same class label. Homogeneity describes the closeness of the clustering algorithm to this perfection.Completeness: A perfectly complete clustering is one where all data-points belonging to the same class are clustered into the same cluster. Completeness describes the closeness of the clustering algorithm to this perfection.
Homogenity: A perfectly homogeneous clustering is one where each cluster has data-points belonging to the same class label. Homogeneity describes the closeness of the clustering algorithm to this perfection.
Completeness: A perfectly complete clustering is one where all data-points belonging to the same class are clustered into the same cluster. Completeness describes the closeness of the clustering algorithm to this perfection.
Trivial Homogeneity: It is the case when the number of clusters is equal to the number of data points and each point is in exactly one cluster. It is the extreme case when homogeneity is highest while completeness is minimum.
Trivial Completeness: It is the case when all the data points are clustered into one cluster. It is the extreme case when homogeneity is minimum and completeness is maximum.
Assume that each data point in the above diagrams is of the different class label for Trivial Homogeneity and Trivial Completeness.
Note: The term homogeneous is different from completeness in the sense that while talking about homogeneity, the base concept is of the respective cluster which we check whether in each cluster does each data point is of the same class label. While talking about completeness, the base concept is of the respective class label which we check whether data points of each class label is in the same cluster.
In the above diagram, the clustering is perfectly homogeneous since in each cluster the data points of are of the same class label but it is not complete because not all data points of the same class label belong to the same class label.
In the above diagram, the clustering is perfectly complete because all data points of the same class label belong to the same cluster but it is not homogeneous because the 1st cluster contains data points of many class labels.
Let us assume that there are N data samples, C different class labels, K clusters and number of data-points belonging to the class c and cluster k. Then the homogeneity h is given by the following:-
where
and
The completeness c is given by the following:-
where
and
Thus the weighted V-Measure is given by the following:-
The factor can be adjusted to favour either the homogeneity or the completeness of the clustering algorithm.
The primary advantage of this evaluation metric is that it is independent of the number of class labels, the number of clusters, the size of the data and the clustering algorithm used and is a very reliable metric.
The following code will demonstrate how to compute the V-Measure of a clustering algorithm. The data used is the Detection of Credit Card Fraud which can be downloaded from Kaggle. The clustering algorithm used is the Variational Bayesian Inference for Gaussian Mixture Model.
Step 1: Importing the required libraries
import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import v_measure_score
Step 2: Loading and Cleaning the data
# Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle\Credit Card Fraud # Loading the datadf = pd.read_csv('creditcard.csv') # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis = 1) X.head()
Step 3: Building different clustering models and comparing their V-Measure scores
In this step, 5 different K-Means Clustering Models will be built with each model clustering the data into a different number of clusters.
# List of V-Measure Scores for different modelsv_scores = [] # List of different types of covariance parametersN_Clusters = [2, 3, 4, 5, 6]
a) n_clusters = 2
# Building the clustering modelkmeans2 = KMeans(n_clusters = 2) # Training the clustering modelkmeans2.fit(X) # Storing the predicted Clustering labelslabels2 = kmeans2.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels2))
b) n_clusters = 3
# Building the clustering modelkmeans3 = KMeans(n_clusters = 3) # Training the clustering modelkmeans3.fit(X) # Storing the predicted Clustering labelslabels3 = kmeans3.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels3))
c) n_clusters = 4
# Building the clustering modelkmeans4 = KMeans(n_clusters = 4) # Training the clustering modelkmeans4.fit(X) # Storing the predicted Clustering labelslabels4 = kmeans4.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels4))
d) n_clusters = 5
# Building the clustering modelkmeans5 = KMeans(n_clusters = 5) # Training the clustering modelkmeans5.fit(X) # Storing the predicted Clustering labelslabels5 = kmeans5.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels5))
e) n_clusters = 6
# Building the clustering modelkmeans6 = KMeans(n_clusters = 6) # Training the clustering modelkmeans6.fit(X) # Storing the predicted Clustering labelslabels6 = kmeans6.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels6))
Step 4: Visualizing the results and comparing the performances
# Plotting a Bar Graph to compare the modelsplt.bar(N_Clusters, v_scores)plt.xlabel('Number of Clusters')plt.ylabel('V-Measure Score')plt.title('Comparison of different Clustering Models')plt.show()
shubham_singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "One of the primary disadvantages of any clustering technique is that it is difficult to evaluate its performance. To tackle this problem, the metric of V-Measure was developed."
},
{
"code": null,
"e": 284,
"s": 205,
"text": "The calculation of the V-Measure first requires the calculation of two terms:-"
},
{
"code": null,
"e": 716,
"s": 284,
"text": "Homogenity: A perfectly homogeneous clustering is one where each cluster has data-points belonging to the same class label. Homogeneity describes the closeness of the clustering algorithm to this perfection.Completeness: A perfectly complete clustering is one where all data-points belonging to the same class are clustered into the same cluster. Completeness describes the closeness of the clustering algorithm to this perfection."
},
{
"code": null,
"e": 924,
"s": 716,
"text": "Homogenity: A perfectly homogeneous clustering is one where each cluster has data-points belonging to the same class label. Homogeneity describes the closeness of the clustering algorithm to this perfection."
},
{
"code": null,
"e": 1149,
"s": 924,
"text": "Completeness: A perfectly complete clustering is one where all data-points belonging to the same class are clustered into the same cluster. Completeness describes the closeness of the clustering algorithm to this perfection."
},
{
"code": null,
"e": 1375,
"s": 1149,
"text": "Trivial Homogeneity: It is the case when the number of clusters is equal to the number of data points and each point is in exactly one cluster. It is the extreme case when homogeneity is highest while completeness is minimum."
},
{
"code": null,
"e": 1549,
"s": 1375,
"text": "Trivial Completeness: It is the case when all the data points are clustered into one cluster. It is the extreme case when homogeneity is minimum and completeness is maximum."
},
{
"code": null,
"e": 1681,
"s": 1549,
"text": "Assume that each data point in the above diagrams is of the different class label for Trivial Homogeneity and Trivial Completeness."
},
{
"code": null,
"e": 2087,
"s": 1681,
"text": "Note: The term homogeneous is different from completeness in the sense that while talking about homogeneity, the base concept is of the respective cluster which we check whether in each cluster does each data point is of the same class label. While talking about completeness, the base concept is of the respective class label which we check whether data points of each class label is in the same cluster."
},
{
"code": null,
"e": 2325,
"s": 2087,
"text": "In the above diagram, the clustering is perfectly homogeneous since in each cluster the data points of are of the same class label but it is not complete because not all data points of the same class label belong to the same class label."
},
{
"code": null,
"e": 2552,
"s": 2325,
"text": "In the above diagram, the clustering is perfectly complete because all data points of the same class label belong to the same cluster but it is not homogeneous because the 1st cluster contains data points of many class labels."
},
{
"code": null,
"e": 2752,
"s": 2552,
"text": "Let us assume that there are N data samples, C different class labels, K clusters and number of data-points belonging to the class c and cluster k. Then the homogeneity h is given by the following:-"
},
{
"code": null,
"e": 2758,
"s": 2752,
"text": "where"
},
{
"code": null,
"e": 2762,
"s": 2758,
"text": "and"
},
{
"code": null,
"e": 2809,
"s": 2762,
"text": "The completeness c is given by the following:-"
},
{
"code": null,
"e": 2815,
"s": 2809,
"text": "where"
},
{
"code": null,
"e": 2819,
"s": 2815,
"text": "and"
},
{
"code": null,
"e": 2876,
"s": 2819,
"text": "Thus the weighted V-Measure is given by the following:-"
},
{
"code": null,
"e": 2986,
"s": 2876,
"text": "The factor can be adjusted to favour either the homogeneity or the completeness of the clustering algorithm."
},
{
"code": null,
"e": 3201,
"s": 2986,
"text": "The primary advantage of this evaluation metric is that it is independent of the number of class labels, the number of clusters, the size of the data and the clustering algorithm used and is a very reliable metric."
},
{
"code": null,
"e": 3478,
"s": 3201,
"text": "The following code will demonstrate how to compute the V-Measure of a clustering algorithm. The data used is the Detection of Credit Card Fraud which can be downloaded from Kaggle. The clustering algorithm used is the Variational Bayesian Inference for Gaussian Mixture Model."
},
{
"code": null,
"e": 3519,
"s": 3478,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import v_measure_score",
"e": 3647,
"s": 3519,
"text": null
},
{
"code": null,
"e": 3685,
"s": 3647,
"text": "Step 2: Loading and Cleaning the data"
},
{
"code": "# Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle\\Credit Card Fraud # Loading the datadf = pd.read_csv('creditcard.csv') # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis = 1) X.head()",
"e": 3956,
"s": 3685,
"text": null
},
{
"code": null,
"e": 4038,
"s": 3956,
"text": "Step 3: Building different clustering models and comparing their V-Measure scores"
},
{
"code": null,
"e": 4177,
"s": 4038,
"text": "In this step, 5 different K-Means Clustering Models will be built with each model clustering the data into a different number of clusters."
},
{
"code": "# List of V-Measure Scores for different modelsv_scores = [] # List of different types of covariance parametersN_Clusters = [2, 3, 4, 5, 6]",
"e": 4318,
"s": 4177,
"text": null
},
{
"code": null,
"e": 4336,
"s": 4318,
"text": "a) n_clusters = 2"
},
{
"code": "# Building the clustering modelkmeans2 = KMeans(n_clusters = 2) # Training the clustering modelkmeans2.fit(X) # Storing the predicted Clustering labelslabels2 = kmeans2.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels2))",
"e": 4592,
"s": 4336,
"text": null
},
{
"code": null,
"e": 4610,
"s": 4592,
"text": "b) n_clusters = 3"
},
{
"code": "# Building the clustering modelkmeans3 = KMeans(n_clusters = 3) # Training the clustering modelkmeans3.fit(X) # Storing the predicted Clustering labelslabels3 = kmeans3.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels3))",
"e": 4866,
"s": 4610,
"text": null
},
{
"code": null,
"e": 4884,
"s": 4866,
"text": "c) n_clusters = 4"
},
{
"code": "# Building the clustering modelkmeans4 = KMeans(n_clusters = 4) # Training the clustering modelkmeans4.fit(X) # Storing the predicted Clustering labelslabels4 = kmeans4.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels4))",
"e": 5140,
"s": 4884,
"text": null
},
{
"code": null,
"e": 5158,
"s": 5140,
"text": "d) n_clusters = 5"
},
{
"code": "# Building the clustering modelkmeans5 = KMeans(n_clusters = 5) # Training the clustering modelkmeans5.fit(X) # Storing the predicted Clustering labelslabels5 = kmeans5.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels5))",
"e": 5414,
"s": 5158,
"text": null
},
{
"code": null,
"e": 5432,
"s": 5414,
"text": "e) n_clusters = 6"
},
{
"code": "# Building the clustering modelkmeans6 = KMeans(n_clusters = 6) # Training the clustering modelkmeans6.fit(X) # Storing the predicted Clustering labelslabels6 = kmeans6.predict(X) # Evaluating the performancev_scores.append(v_measure_score(y, labels6))",
"e": 5688,
"s": 5432,
"text": null
},
{
"code": null,
"e": 5751,
"s": 5688,
"text": "Step 4: Visualizing the results and comparing the performances"
},
{
"code": "# Plotting a Bar Graph to compare the modelsplt.bar(N_Clusters, v_scores)plt.xlabel('Number of Clusters')plt.ylabel('V-Measure Score')plt.title('Comparison of different Clustering Models')plt.show()",
"e": 5950,
"s": 5751,
"text": null
},
{
"code": null,
"e": 5964,
"s": 5950,
"text": "shubham_singh"
},
{
"code": null,
"e": 5981,
"s": 5964,
"text": "Machine Learning"
},
{
"code": null,
"e": 5988,
"s": 5981,
"text": "Python"
},
{
"code": null,
"e": 6005,
"s": 5988,
"text": "Machine Learning"
}
]
|
R – Variables | 23 May, 2022
A variable is a memory allocated for the storage of specific data and the name associated with the variable is used to work around this reserved block. The name given to a variable is known as its variable name. Usually a single variable stores only the data belonging to a certain data type. The name is so given to them because when the program executes there is subject to change hence it varies from time to time.
R Programming Language is a dynamically typed language, i.e. the R Language Variables are not declared with a data type rather they take the data type of the R-object assigned to them. This feature is also shown in languages like Python and PHP.
R supports three ways of variable assignment:
Using equal operator- data is copied from right to left.
Using leftward operator- data is copied from right to left.
Using rightward operator- data is copied from left to right.
#using equal to operator
variable_name = value
#using leftward operator
variable_name <- value
#using rightward operator
value -> variable_name
R
# R program to illustrate# Initialization of variables # using equal to operatorvar1 = "hello"print(var1) # using leftward operatorvar2 < - "hello"print(var2) # using rightward operator"hello" -> var3print(var3)
Output:
[1] "hello"
[1] "hello"
[1] "hello"
The following rules need to be kept in mind while naming a variable:
A valid variable name consists of a combination of alphabets, numbers, dot(.), and underscore(_) characters. Example: var.1_ is valid
Apart from the dot and underscore operators, no other special character is allowed. Example: var$1 or var#1 both are invalid
Variables can start with alphabets or dot characters. Example: .var or var is valid
The variable should not start with numbers or underscore. Example: 2var or _var is invalid.
If a variable starts with a dot the next thing after the dot cannot be a number. Example: .3var is invalid
R provides some useful methods to perform operations on variables. These methods are used to determine the data type of the variable, finding a variable, deleting a variable, etc. Following are some of the methods used to work on variables:
This built-in function is used to determine the data type of the variable provided to it. The variable to be checked is passed to this as an argument and it prints the data type in return.
Syntax:
class(variable)
Example:
R
var1 = "hello"print(class(var1))
Output:
[1] "character"
This built-in function is used to know all the present variables in the workspace. This is generally helpful when dealing with a large number of variables at once and helps prevents overwriting any of them.
Syntax:
ls()
Example:
R
# using equal to operatorvar1 = "hello" # using leftward operatorvar2 < - "hello" # using rightward operator"hello" -> var3 print(ls())
Output:
[1] "var1" "var2" "var3"
This is again a built-in function used to delete an unwanted variable within your workspace. This helps clear the memory space allocated to certain variables that are not in use thereby creating more space for others. The name of the variable to be deleted is passed as an argument to it.
Syntax:
rm(variable)
Example:
R
# using equal to operatorvar1 = "hello" # using leftward operatorvar2 < - "hello" # using rightward operator"hello" -> var3 # Removing variablerm(var3)print(var3)
Output:
Error in print(var3) : object 'var3' not found
Execution halted
The location where we can find a variable and also access it if required is called the scope of a variable. There are mainly two types of variable scopes:
Global variables are those variables that exist throughout the execution of a program. It can be changed and accessed from any part of the program.
As the name suggests, Global Variables can be accessed from any part of the program.
They are available throughout the lifetime of a program.
They are declared anywhere in the program outside all of the functions or blocks.
Declaring global variables: Global variables are usually declared outside of all of the functions and blocks. They can be accessed from any portion of the program.
R
# R program to illustrate# usage of global variables # global variableglobal = 5 # global variable accessed from# within a functiondisplay = function(){print(global)}display() # changing value of global variableglobal = 10display()
Output:
[1] 5
[1] 10
In the above code, the variable ‘global’ is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.
Local variables are those variables that exist only within a certain part of a program like a function and are released when the function call ends. Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.
Declaring local variables:
Local variables are declared inside a block.
R
# R program to illustrate# usage of local variables func = function(){# this variable is local to the# function func() and cannot be# accessed outside this functionage = 18 print(age)} cat("Age is:\n")func()
Output:
Age is:
[1] 18
kumar_satyam
sweetyty
Picked
R-Variables
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "A variable is a memory allocated for the storage of specific data and the name associated with the variable is used to work around this reserved block. The name given to a variable is known as its variable name. Usually a single variable stores only the data belonging to a certain data type. The name is so given to them because when the program executes there is subject to change hence it varies from time to time."
},
{
"code": null,
"e": 693,
"s": 446,
"text": "R Programming Language is a dynamically typed language, i.e. the R Language Variables are not declared with a data type rather they take the data type of the R-object assigned to them. This feature is also shown in languages like Python and PHP."
},
{
"code": null,
"e": 739,
"s": 693,
"text": "R supports three ways of variable assignment:"
},
{
"code": null,
"e": 796,
"s": 739,
"text": "Using equal operator- data is copied from right to left."
},
{
"code": null,
"e": 856,
"s": 796,
"text": "Using leftward operator- data is copied from right to left."
},
{
"code": null,
"e": 917,
"s": 856,
"text": "Using rightward operator- data is copied from left to right."
},
{
"code": null,
"e": 943,
"s": 917,
"text": "#using equal to operator "
},
{
"code": null,
"e": 965,
"s": 943,
"text": "variable_name = value"
},
{
"code": null,
"e": 991,
"s": 965,
"text": "#using leftward operator "
},
{
"code": null,
"e": 1014,
"s": 991,
"text": "variable_name <- value"
},
{
"code": null,
"e": 1041,
"s": 1014,
"text": "#using rightward operator "
},
{
"code": null,
"e": 1064,
"s": 1041,
"text": "value -> variable_name"
},
{
"code": null,
"e": 1066,
"s": 1064,
"text": "R"
},
{
"code": "# R program to illustrate# Initialization of variables # using equal to operatorvar1 = \"hello\"print(var1) # using leftward operatorvar2 < - \"hello\"print(var2) # using rightward operator\"hello\" -> var3print(var3)",
"e": 1278,
"s": 1066,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1278,
"text": "Output: "
},
{
"code": null,
"e": 1323,
"s": 1287,
"text": "[1] \"hello\"\n[1] \"hello\"\n[1] \"hello\""
},
{
"code": null,
"e": 1393,
"s": 1323,
"text": "The following rules need to be kept in mind while naming a variable: "
},
{
"code": null,
"e": 1527,
"s": 1393,
"text": "A valid variable name consists of a combination of alphabets, numbers, dot(.), and underscore(_) characters. Example: var.1_ is valid"
},
{
"code": null,
"e": 1652,
"s": 1527,
"text": "Apart from the dot and underscore operators, no other special character is allowed. Example: var$1 or var#1 both are invalid"
},
{
"code": null,
"e": 1736,
"s": 1652,
"text": "Variables can start with alphabets or dot characters. Example: .var or var is valid"
},
{
"code": null,
"e": 1828,
"s": 1736,
"text": "The variable should not start with numbers or underscore. Example: 2var or _var is invalid."
},
{
"code": null,
"e": 1935,
"s": 1828,
"text": "If a variable starts with a dot the next thing after the dot cannot be a number. Example: .3var is invalid"
},
{
"code": null,
"e": 2176,
"s": 1935,
"text": "R provides some useful methods to perform operations on variables. These methods are used to determine the data type of the variable, finding a variable, deleting a variable, etc. Following are some of the methods used to work on variables:"
},
{
"code": null,
"e": 2365,
"s": 2176,
"text": "This built-in function is used to determine the data type of the variable provided to it. The variable to be checked is passed to this as an argument and it prints the data type in return."
},
{
"code": null,
"e": 2373,
"s": 2365,
"text": "Syntax:"
},
{
"code": null,
"e": 2390,
"s": 2373,
"text": "class(variable) "
},
{
"code": null,
"e": 2400,
"s": 2390,
"text": "Example: "
},
{
"code": null,
"e": 2402,
"s": 2400,
"text": "R"
},
{
"code": "var1 = \"hello\"print(class(var1))",
"e": 2435,
"s": 2402,
"text": null
},
{
"code": null,
"e": 2444,
"s": 2435,
"text": "Output: "
},
{
"code": null,
"e": 2460,
"s": 2444,
"text": "[1] \"character\""
},
{
"code": null,
"e": 2667,
"s": 2460,
"text": "This built-in function is used to know all the present variables in the workspace. This is generally helpful when dealing with a large number of variables at once and helps prevents overwriting any of them."
},
{
"code": null,
"e": 2676,
"s": 2667,
"text": "Syntax: "
},
{
"code": null,
"e": 2683,
"s": 2676,
"text": " ls() "
},
{
"code": null,
"e": 2693,
"s": 2683,
"text": "Example: "
},
{
"code": null,
"e": 2695,
"s": 2693,
"text": "R"
},
{
"code": "# using equal to operatorvar1 = \"hello\" # using leftward operatorvar2 < - \"hello\" # using rightward operator\"hello\" -> var3 print(ls())",
"e": 2831,
"s": 2695,
"text": null
},
{
"code": null,
"e": 2840,
"s": 2831,
"text": "Output: "
},
{
"code": null,
"e": 2865,
"s": 2840,
"text": "[1] \"var1\" \"var2\" \"var3\""
},
{
"code": null,
"e": 3154,
"s": 2865,
"text": "This is again a built-in function used to delete an unwanted variable within your workspace. This helps clear the memory space allocated to certain variables that are not in use thereby creating more space for others. The name of the variable to be deleted is passed as an argument to it."
},
{
"code": null,
"e": 3163,
"s": 3154,
"text": "Syntax: "
},
{
"code": null,
"e": 3178,
"s": 3163,
"text": " rm(variable) "
},
{
"code": null,
"e": 3188,
"s": 3178,
"text": "Example: "
},
{
"code": null,
"e": 3190,
"s": 3188,
"text": "R"
},
{
"code": "# using equal to operatorvar1 = \"hello\" # using leftward operatorvar2 < - \"hello\" # using rightward operator\"hello\" -> var3 # Removing variablerm(var3)print(var3)",
"e": 3353,
"s": 3190,
"text": null
},
{
"code": null,
"e": 3361,
"s": 3353,
"text": "Output:"
},
{
"code": null,
"e": 3426,
"s": 3361,
"text": "Error in print(var3) : object 'var3' not found\nExecution halted "
},
{
"code": null,
"e": 3581,
"s": 3426,
"text": "The location where we can find a variable and also access it if required is called the scope of a variable. There are mainly two types of variable scopes:"
},
{
"code": null,
"e": 3729,
"s": 3581,
"text": "Global variables are those variables that exist throughout the execution of a program. It can be changed and accessed from any part of the program."
},
{
"code": null,
"e": 3814,
"s": 3729,
"text": "As the name suggests, Global Variables can be accessed from any part of the program."
},
{
"code": null,
"e": 3871,
"s": 3814,
"text": "They are available throughout the lifetime of a program."
},
{
"code": null,
"e": 3953,
"s": 3871,
"text": "They are declared anywhere in the program outside all of the functions or blocks."
},
{
"code": null,
"e": 4117,
"s": 3953,
"text": "Declaring global variables: Global variables are usually declared outside of all of the functions and blocks. They can be accessed from any portion of the program."
},
{
"code": null,
"e": 4119,
"s": 4117,
"text": "R"
},
{
"code": "# R program to illustrate# usage of global variables # global variableglobal = 5 # global variable accessed from# within a functiondisplay = function(){print(global)}display() # changing value of global variableglobal = 10display()",
"e": 4351,
"s": 4119,
"text": null
},
{
"code": null,
"e": 4359,
"s": 4351,
"text": "Output:"
},
{
"code": null,
"e": 4372,
"s": 4359,
"text": "[1] 5\n[1] 10"
},
{
"code": null,
"e": 4568,
"s": 4372,
"text": "In the above code, the variable ‘global’ is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program."
},
{
"code": null,
"e": 4850,
"s": 4568,
"text": "Local variables are those variables that exist only within a certain part of a program like a function and are released when the function call ends. Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block."
},
{
"code": null,
"e": 4878,
"s": 4850,
"text": "Declaring local variables: "
},
{
"code": null,
"e": 4923,
"s": 4878,
"text": "Local variables are declared inside a block."
},
{
"code": null,
"e": 4925,
"s": 4923,
"text": "R"
},
{
"code": "# R program to illustrate# usage of local variables func = function(){# this variable is local to the# function func() and cannot be# accessed outside this functionage = 18 print(age)} cat(\"Age is:\\n\")func()",
"e": 5135,
"s": 4925,
"text": null
},
{
"code": null,
"e": 5143,
"s": 5135,
"text": "Output:"
},
{
"code": null,
"e": 5158,
"s": 5143,
"text": "Age is:\n[1] 18"
},
{
"code": null,
"e": 5171,
"s": 5158,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5180,
"s": 5171,
"text": "sweetyty"
},
{
"code": null,
"e": 5187,
"s": 5180,
"text": "Picked"
},
{
"code": null,
"e": 5199,
"s": 5187,
"text": "R-Variables"
},
{
"code": null,
"e": 5210,
"s": 5199,
"text": "R Language"
}
]
|
vector data() function in C++ STL | 09 Jun, 2022
The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.
Syntax:
vector_name.data()
Parameters: The function does not accept any parameters.Return value: The function returns a pointer to the first element in the array which is used internally by the vector.
Time Complexity – Constant O(1)
Below program illustrate the above function:
CPP
// C++ program to demonstrate the// vector::date() function#include <bits/stdc++.h>using namespace std; int main(){ // initialising vector vector<int> vec = { 10, 20, 30, 40, 50 }; // memory pointer pointing to the // first element int* pos = vec.data(); // prints the vector cout << "The vector elements are: "; for (int i = 0; i < vec.size(); ++i) cout << *pos++ << " "; return 0;}
The vector elements are: 10 20 30 40 50
sunilpanda20022002
utkarshgupta110092
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 53,
"text": "The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements. "
},
{
"code": null,
"e": 214,
"s": 205,
"text": "Syntax: "
},
{
"code": null,
"e": 233,
"s": 214,
"text": "vector_name.data()"
},
{
"code": null,
"e": 408,
"s": 233,
"text": "Parameters: The function does not accept any parameters.Return value: The function returns a pointer to the first element in the array which is used internally by the vector."
},
{
"code": null,
"e": 440,
"s": 408,
"text": "Time Complexity – Constant O(1)"
},
{
"code": null,
"e": 485,
"s": 440,
"text": "Below program illustrate the above function:"
},
{
"code": null,
"e": 489,
"s": 485,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the// vector::date() function#include <bits/stdc++.h>using namespace std; int main(){ // initialising vector vector<int> vec = { 10, 20, 30, 40, 50 }; // memory pointer pointing to the // first element int* pos = vec.data(); // prints the vector cout << \"The vector elements are: \"; for (int i = 0; i < vec.size(); ++i) cout << *pos++ << \" \"; return 0;}",
"e": 910,
"s": 489,
"text": null
},
{
"code": null,
"e": 951,
"s": 910,
"text": "The vector elements are: 10 20 30 40 50 "
},
{
"code": null,
"e": 970,
"s": 951,
"text": "sunilpanda20022002"
},
{
"code": null,
"e": 989,
"s": 970,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 1003,
"s": 989,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1014,
"s": 1003,
"text": "cpp-vector"
},
{
"code": null,
"e": 1018,
"s": 1014,
"text": "STL"
},
{
"code": null,
"e": 1022,
"s": 1018,
"text": "C++"
},
{
"code": null,
"e": 1026,
"s": 1022,
"text": "STL"
},
{
"code": null,
"e": 1030,
"s": 1026,
"text": "CPP"
},
{
"code": null,
"e": 1128,
"s": 1030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1152,
"s": 1128,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1172,
"s": 1152,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1197,
"s": 1172,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1230,
"s": 1197,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1274,
"s": 1230,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1319,
"s": 1274,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1367,
"s": 1319,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1384,
"s": 1367,
"text": "std::find in C++"
},
{
"code": null,
"e": 1428,
"s": 1384,
"text": "List in C++ Standard Template Library (STL)"
}
]
|
Java Program to Check Whether a Matrix is Symmetric or Not | 03 Nov, 2021
A symmetric matrix is a square matrix in which the transpose of the square matrix is the same as the original square matrix. A square matrix is a matrix in which the number of columns is the same as the number of rows. If the matrix is a symmetric matrix then it is also a square matrix but vice versa isn’t true. Matrix is simply considered as 2D arrays for action to be performed. Here, we are going to see the approach to check if the entered square matrix is symmetric or not.
Illustration:
Input : 6 5 2
5 0 9
2 9 3
Output: The matrix is symmetric
Input : 6 1 2
5 0 9
2 9 3
Output: The matrix is not symmetric
Approach:
Take the matrix as an input from the user
Find transpose of the matrix
Compare two matrices
If the two matrices is the same then it is symmetric otherwise it’s not.
Implementation:
Example
Java
// Java Program to check whether matrix is// symmetric or not // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // Matrix 1 // Method to check whether the matrix is // symmetric or asymmetric static void checkSymmetric(int mat[][], int row, int col) { int i, j, flag = 1; // Display message System.out.println("The matrix formed is:"); // Nested for loop for matrix iteration // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix System.out.print(mat[i][j] + "\t"); } System.out.println(""); } // Matrix 2 // Finding transpose of the matrix int[][] transpose = new int[row][col]; // Again, nested for loop for matrix iteration // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix elements transpose[j][i] = mat[i][j]; } } // Condition check over Matrix 1 with Matrix 2 if (row == col) { // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Comparing two matrices if (mat[i][j] != transpose[i][j]) { flag = 0; break; } } // Setting a flag value for symmetric matrix if (flag == 0) { // Display message System.out.print( "\nThe matrix is not symmetric"); break; } } // Setting a flag value different from above // for symmetric matrix if (flag == 1) { // Display message System.out.print( "\nThe matrix is symmetric"); } } // If it isn't a square matrix // then it can't be a symmetric matrix else { // Display message System.out.print( "\nThe matrix is not symmetric"); } } // Main driver method public static void main(String args[]) { // Taking input from the user Scanner sc = new Scanner(System.in); // Declaring variables and setting flag to 1 int i, j, row, col, flag = 1; // Taking input from the user System.out.print("Enter the number of rows:"); row = sc.nextInt(); // Display message System.out.print("Enter the number of columns:"); // Reading matrix elements individually using // nextInt() method col = sc.nextInt(); // Declaring a 2D array(matrix) int[][] mat = new int[row][col]; // Display message System.out.println("Enter the matrix elements:"); // Nested for loop for traversing matrix // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix element mat[i][j] = sc.nextInt(); } } // calling function made above to check // whether matrix is symmetric or not checkSymmetric(mat, row, col); }}
Output: Below both symmmericity and asymetricity is checked as follows:
sweetyty
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": "\n03 Nov, 2021"
},
{
"code": null,
"e": 509,
"s": 28,
"text": "A symmetric matrix is a square matrix in which the transpose of the square matrix is the same as the original square matrix. A square matrix is a matrix in which the number of columns is the same as the number of rows. If the matrix is a symmetric matrix then it is also a square matrix but vice versa isn’t true. Matrix is simply considered as 2D arrays for action to be performed. Here, we are going to see the approach to check if the entered square matrix is symmetric or not."
},
{
"code": null,
"e": 523,
"s": 509,
"text": "Illustration:"
},
{
"code": null,
"e": 676,
"s": 523,
"text": "Input : 6 5 2\n 5 0 9\n 2 9 3\nOutput: The matrix is symmetric\n\nInput : 6 1 2\n 5 0 9\n 2 9 3\nOutput: The matrix is not symmetric"
},
{
"code": null,
"e": 687,
"s": 676,
"text": "Approach: "
},
{
"code": null,
"e": 729,
"s": 687,
"text": "Take the matrix as an input from the user"
},
{
"code": null,
"e": 758,
"s": 729,
"text": "Find transpose of the matrix"
},
{
"code": null,
"e": 779,
"s": 758,
"text": "Compare two matrices"
},
{
"code": null,
"e": 852,
"s": 779,
"text": "If the two matrices is the same then it is symmetric otherwise it’s not."
},
{
"code": null,
"e": 868,
"s": 852,
"text": "Implementation:"
},
{
"code": null,
"e": 876,
"s": 868,
"text": "Example"
},
{
"code": null,
"e": 881,
"s": 876,
"text": "Java"
},
{
"code": "// Java Program to check whether matrix is// symmetric or not // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // Matrix 1 // Method to check whether the matrix is // symmetric or asymmetric static void checkSymmetric(int mat[][], int row, int col) { int i, j, flag = 1; // Display message System.out.println(\"The matrix formed is:\"); // Nested for loop for matrix iteration // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix System.out.print(mat[i][j] + \"\\t\"); } System.out.println(\"\"); } // Matrix 2 // Finding transpose of the matrix int[][] transpose = new int[row][col]; // Again, nested for loop for matrix iteration // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix elements transpose[j][i] = mat[i][j]; } } // Condition check over Matrix 1 with Matrix 2 if (row == col) { // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Comparing two matrices if (mat[i][j] != transpose[i][j]) { flag = 0; break; } } // Setting a flag value for symmetric matrix if (flag == 0) { // Display message System.out.print( \"\\nThe matrix is not symmetric\"); break; } } // Setting a flag value different from above // for symmetric matrix if (flag == 1) { // Display message System.out.print( \"\\nThe matrix is symmetric\"); } } // If it isn't a square matrix // then it can't be a symmetric matrix else { // Display message System.out.print( \"\\nThe matrix is not symmetric\"); } } // Main driver method public static void main(String args[]) { // Taking input from the user Scanner sc = new Scanner(System.in); // Declaring variables and setting flag to 1 int i, j, row, col, flag = 1; // Taking input from the user System.out.print(\"Enter the number of rows:\"); row = sc.nextInt(); // Display message System.out.print(\"Enter the number of columns:\"); // Reading matrix elements individually using // nextInt() method col = sc.nextInt(); // Declaring a 2D array(matrix) int[][] mat = new int[row][col]; // Display message System.out.println(\"Enter the matrix elements:\"); // Nested for loop for traversing matrix // Outer loop for rows for (i = 0; i < row; i++) { // Inner loop for columns for (j = 0; j < col; j++) { // Print matrix element mat[i][j] = sc.nextInt(); } } // calling function made above to check // whether matrix is symmetric or not checkSymmetric(mat, row, col); }}",
"e": 4429,
"s": 881,
"text": null
},
{
"code": null,
"e": 4501,
"s": 4429,
"text": "Output: Below both symmmericity and asymetricity is checked as follows:"
},
{
"code": null,
"e": 4510,
"s": 4501,
"text": "sweetyty"
},
{
"code": null,
"e": 4517,
"s": 4510,
"text": "Picked"
},
{
"code": null,
"e": 4522,
"s": 4517,
"text": "Java"
},
{
"code": null,
"e": 4536,
"s": 4522,
"text": "Java Programs"
},
{
"code": null,
"e": 4541,
"s": 4536,
"text": "Java"
},
{
"code": null,
"e": 4639,
"s": 4541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4654,
"s": 4639,
"text": "Stream In Java"
},
{
"code": null,
"e": 4675,
"s": 4654,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4696,
"s": 4675,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4715,
"s": 4696,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4732,
"s": 4715,
"text": "Generics in Java"
},
{
"code": null,
"e": 4758,
"s": 4732,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4792,
"s": 4758,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 4839,
"s": 4792,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 4877,
"s": 4839,
"text": "Factory method design pattern in Java"
}
]
|
IntStream mapToLong() in Java - GeeksforGeeks | 06 Dec, 2018
IntStream mapToLong() returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Note : IntStream mapToLong() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax :
LongStream mapToLong(IntToLongFunction mapper)
Parameters :
LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream.mapper : A stateless function to apply to each element.
LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream.
mapper : A stateless function to apply to each element.
Return Value : The function returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Example 1 :
// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, 8, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}
Output :
2
4
6
8
10
Example 2 :
// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, 8, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num + Integer.MAX_VALUE); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}
Output :
2147483649
2147483651
2147483653
2147483655
2147483657
Example 3 :
// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(5, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num - 20); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}
Output :
-15
-14
-13
-12
-11
Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 25357,
"s": 25225,
"text": "IntStream mapToLong() returns a LongStream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 25593,
"s": 25357,
"text": "Note : IntStream mapToLong() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax :"
},
{
"code": null,
"e": 25641,
"s": 25593,
"text": "LongStream mapToLong(IntToLongFunction mapper)\n"
},
{
"code": null,
"e": 25654,
"s": 25641,
"text": "Parameters :"
},
{
"code": null,
"e": 25821,
"s": 25654,
"text": "LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream.mapper : A stateless function to apply to each element."
},
{
"code": null,
"e": 25933,
"s": 25821,
"text": "LongStream : A sequence of primitive long-valued elements. This is the long primitive specialization of Stream."
},
{
"code": null,
"e": 25989,
"s": 25933,
"text": "mapper : A stateless function to apply to each element."
},
{
"code": null,
"e": 26127,
"s": 25989,
"text": "Return Value : The function returns a LongStream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 26139,
"s": 26127,
"text": "Example 1 :"
},
{
"code": "// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, 8, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}",
"e": 26831,
"s": 26139,
"text": null
},
{
"code": null,
"e": 26840,
"s": 26831,
"text": "Output :"
},
{
"code": null,
"e": 26852,
"s": 26840,
"text": "2\n4\n6\n8\n10\n"
},
{
"code": null,
"e": 26864,
"s": 26852,
"text": "Example 2 :"
},
{
"code": "// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, 8, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num + Integer.MAX_VALUE); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}",
"e": 27576,
"s": 26864,
"text": null
},
{
"code": null,
"e": 27585,
"s": 27576,
"text": "Output :"
},
{
"code": null,
"e": 27641,
"s": 27585,
"text": "2147483649\n2147483651\n2147483653\n2147483655\n2147483657\n"
},
{
"code": null,
"e": 27653,
"s": 27641,
"text": "Example 3 :"
},
{
"code": "// Java code for LongStream mapToLong// (IntToLongFunction mapper)import java.util.*;import java.util.stream.IntStream;import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(5, 10); // Using LongStream mapToLong(IntToLongFunction mapper) // to return a LongStream consisting of the // results of applying the given function to // the elements of this stream. LongStream stream1 = stream.mapToLong(num -> (long)num - 20); // Displaying the elements in stream1 stream1.forEach(System.out::println); }}",
"e": 28344,
"s": 27653,
"text": null
},
{
"code": null,
"e": 28353,
"s": 28344,
"text": "Output :"
},
{
"code": null,
"e": 28374,
"s": 28353,
"text": "-15\n-14\n-13\n-12\n-11\n"
},
{
"code": null,
"e": 28394,
"s": 28374,
"text": "Java - util package"
},
{
"code": null,
"e": 28409,
"s": 28394,
"text": "Java-Functions"
},
{
"code": null,
"e": 28424,
"s": 28409,
"text": "java-intstream"
},
{
"code": null,
"e": 28436,
"s": 28424,
"text": "java-stream"
},
{
"code": null,
"e": 28441,
"s": 28436,
"text": "Java"
},
{
"code": null,
"e": 28446,
"s": 28441,
"text": "Java"
},
{
"code": null,
"e": 28544,
"s": 28446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28559,
"s": 28544,
"text": "Stream In Java"
},
{
"code": null,
"e": 28580,
"s": 28559,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28599,
"s": 28580,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28629,
"s": 28599,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28675,
"s": 28629,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28692,
"s": 28675,
"text": "Generics in Java"
},
{
"code": null,
"e": 28713,
"s": 28692,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28756,
"s": 28713,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28792,
"s": 28756,
"text": "Internal Working of HashMap in Java"
}
]
|
Python NLTK | nltk.WhitespaceTokenizer - GeeksforGeeks | 07 Jun, 2019
With the help of nltk.tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from string of words or sentences without whitespaces, new line and tabs by using tokenize.WhitespaceTokenizer() method.
Syntax : tokenize.WhitespaceTokenizer()Return : Return the tokens from a string
Example #1 :In this example we can see that by using tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from stream of words.
# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer() # Create a string inputgfg = "GeeksforGeeks \nis\t for geeks" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘GeeksforGeeks’, ‘is’, ‘for’, ‘geeks’]
Example #2 :
# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer() # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs.36.’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25707,
"s": 25679,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 25923,
"s": 25707,
"text": "With the help of nltk.tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from string of words or sentences without whitespaces, new line and tabs by using tokenize.WhitespaceTokenizer() method."
},
{
"code": null,
"e": 26003,
"s": 25923,
"text": "Syntax : tokenize.WhitespaceTokenizer()Return : Return the tokens from a string"
},
{
"code": null,
"e": 26151,
"s": 26003,
"text": "Example #1 :In this example we can see that by using tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from stream of words."
},
{
"code": "# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer() # Create a string inputgfg = \"GeeksforGeeks \\nis\\t for geeks\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 26465,
"s": 26151,
"text": null
},
{
"code": null,
"e": 26474,
"s": 26465,
"text": "Output :"
},
{
"code": null,
"e": 26514,
"s": 26474,
"text": "[‘GeeksforGeeks’, ‘is’, ‘for’, ‘geeks’]"
},
{
"code": null,
"e": 26527,
"s": 26514,
"text": "Example #2 :"
},
{
"code": "# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer() # Create a string inputgfg = \"The price\\t of burger \\nin BurgerKing is Rs.36.\\n\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 26860,
"s": 26527,
"text": null
},
{
"code": null,
"e": 26869,
"s": 26860,
"text": "Output :"
},
{
"code": null,
"e": 26938,
"s": 26869,
"text": "[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs.36.’]"
},
{
"code": null,
"e": 26950,
"s": 26938,
"text": "Python-nltk"
},
{
"code": null,
"e": 26957,
"s": 26950,
"text": "Python"
},
{
"code": null,
"e": 27055,
"s": 26957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27073,
"s": 27055,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27105,
"s": 27073,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27127,
"s": 27105,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27169,
"s": 27127,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27195,
"s": 27169,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27224,
"s": 27195,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27261,
"s": 27224,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27297,
"s": 27261,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27339,
"s": 27297,
"text": "Check if element exists in list in Python"
}
]
|
What is the difference between field, variable, attribute, and property in Java - GeeksforGeeks | 28 Mar, 2022
Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some people like to call final non-static variables. In Java, all the variables must be declared before use. Field A data member of a class. Unless specified otherwise, a field can be public, static, not static and final.
JAVA
public class Customer { // Fields of customer final String field1 = "Fixed Value"; int name;}
Attribute An attribute is another term for a field. It’s typically a public field that can be accessed directly. Let’s see a particular case of Array, the array is actually an object and you are accessing the public constant value that represents the length of the array. In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion those suggestion is called Attribute. Note: Here Never Show Private Fields Property It is also used for fields, it typically has getter and setter combination. Example:
JAVA
public class Test { private int number; public int getNumber() { return this.number; } public void setNumber(int num) { this.number = num; }}
JAVA
public class Variables { // Constant public final static String name = "robot"; // Value final String dontChange = "India"; // Field protected String river = "GANGA"; // Property private String age; // Still the property public String getAge() { return this.age; } // And now the setter public void setAge(String age) { this.age = age; }}
sagartomar9927
java-basics
Technical Scripter 2018
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 25819,
"s": 25251,
"text": "Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some people like to call final non-static variables. In Java, all the variables must be declared before use. Field A data member of a class. Unless specified otherwise, a field can be public, static, not static and final. "
},
{
"code": null,
"e": 25824,
"s": 25819,
"text": "JAVA"
},
{
"code": "public class Customer { // Fields of customer final String field1 = \"Fixed Value\"; int name;}",
"e": 25928,
"s": 25824,
"text": null
},
{
"code": null,
"e": 26474,
"s": 25928,
"text": "Attribute An attribute is another term for a field. It’s typically a public field that can be accessed directly. Let’s see a particular case of Array, the array is actually an object and you are accessing the public constant value that represents the length of the array. In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion those suggestion is called Attribute. Note: Here Never Show Private Fields Property It is also used for fields, it typically has getter and setter combination. Example: "
},
{
"code": null,
"e": 26479,
"s": 26474,
"text": "JAVA"
},
{
"code": "public class Test { private int number; public int getNumber() { return this.number; } public void setNumber(int num) { this.number = num; }}",
"e": 26658,
"s": 26479,
"text": null
},
{
"code": null,
"e": 26667,
"s": 26662,
"text": "JAVA"
},
{
"code": "public class Variables { // Constant public final static String name = \"robot\"; // Value final String dontChange = \"India\"; // Field protected String river = \"GANGA\"; // Property private String age; // Still the property public String getAge() { return this.age; } // And now the setter public void setAge(String age) { this.age = age; }}",
"e": 27074,
"s": 26667,
"text": null
},
{
"code": null,
"e": 27089,
"s": 27074,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27101,
"s": 27089,
"text": "java-basics"
},
{
"code": null,
"e": 27125,
"s": 27101,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27130,
"s": 27125,
"text": "Java"
},
{
"code": null,
"e": 27149,
"s": 27130,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27154,
"s": 27149,
"text": "Java"
},
{
"code": null,
"e": 27252,
"s": 27154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27267,
"s": 27252,
"text": "Stream In Java"
},
{
"code": null,
"e": 27288,
"s": 27267,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27307,
"s": 27288,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27337,
"s": 27307,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27383,
"s": 27337,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27400,
"s": 27383,
"text": "Generics in Java"
},
{
"code": null,
"e": 27421,
"s": 27400,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27464,
"s": 27421,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27500,
"s": 27464,
"text": "Internal Working of HashMap in Java"
}
]
|
How to Install Ruby on Termux? - GeeksforGeeks | 11 Apr, 2022
Ruby is an open-source programming language. It can be installed in any operating system. It is an interpreted, high-level object-oriented programming language. It was first implemented in the mid-1990s in Japan. It was developed & designed by Yukihiro “Martz” Matsumoto. The developer wants a programming language that is completely object-oriented. As he could not find any he developed Ruby.
Ruby is completely an object-oriented programming language.
In Ruby, it has been seen that the development code is much faster than other programming languages.
Follow the below steps to install Ruby on Termux:
Step 1: To install Ruby in termux first you have to install termux in your android.
Step 2: Open termux in mobile.
Step 3: Then we have to write the below commands like
$ cd . .
$ cd usr/
$ cd etc/
$ cd apt
$ ls
Then we have to wait for some time.
Step 4: Again we have to write the below command:
$ nano sources.list
Step 5:Now enter the below link as :
deb https://termux.net stable main
Step 6: Now again run the below command:
$ cd sources.list.d/
$ mv *.list ../
$ ls
$ cd . .
$ apt update
Step 7: Then run the below command to install Ruby:
$ pkg install ruby
Step 8: Now enter “Y” when prompted:
Step 9: Then we have to run the following link:
echo "export LD_LIBRARY_PATH=/data/data/com.termux/files/usr/lib">>-/.bashrc
Step 10: Then we have to run the below command to exit from termux:
$ exit
Use the below command to verify the Ruby installation on Termux:
$ ruby
$ ruby -v
Congratulation. At this point, you have successfully installed Ruby on Termux.
sumitgumber28
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
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": 26197,
"s": 26169,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 26592,
"s": 26197,
"text": "Ruby is an open-source programming language. It can be installed in any operating system. It is an interpreted, high-level object-oriented programming language. It was first implemented in the mid-1990s in Japan. It was developed & designed by Yukihiro “Martz” Matsumoto. The developer wants a programming language that is completely object-oriented. As he could not find any he developed Ruby."
},
{
"code": null,
"e": 26652,
"s": 26592,
"text": "Ruby is completely an object-oriented programming language."
},
{
"code": null,
"e": 26753,
"s": 26652,
"text": "In Ruby, it has been seen that the development code is much faster than other programming languages."
},
{
"code": null,
"e": 26803,
"s": 26753,
"text": "Follow the below steps to install Ruby on Termux:"
},
{
"code": null,
"e": 26887,
"s": 26803,
"text": "Step 1: To install Ruby in termux first you have to install termux in your android."
},
{
"code": null,
"e": 26918,
"s": 26887,
"text": "Step 2: Open termux in mobile."
},
{
"code": null,
"e": 26972,
"s": 26918,
"text": "Step 3: Then we have to write the below commands like"
},
{
"code": null,
"e": 27015,
"s": 26972,
"text": "$ cd . .\n$ cd usr/\n$ cd etc/\n$ cd apt\n$ ls"
},
{
"code": null,
"e": 27051,
"s": 27015,
"text": "Then we have to wait for some time."
},
{
"code": null,
"e": 27101,
"s": 27051,
"text": "Step 4: Again we have to write the below command:"
},
{
"code": null,
"e": 27121,
"s": 27101,
"text": "$ nano sources.list"
},
{
"code": null,
"e": 27159,
"s": 27121,
"text": "Step 5:Now enter the below link as :"
},
{
"code": null,
"e": 27194,
"s": 27159,
"text": "deb https://termux.net stable main"
},
{
"code": null,
"e": 27235,
"s": 27194,
"text": "Step 6: Now again run the below command:"
},
{
"code": null,
"e": 27299,
"s": 27235,
"text": "$ cd sources.list.d/\n$ mv *.list ../\n$ ls\n$ cd . .\n$ apt update"
},
{
"code": null,
"e": 27351,
"s": 27299,
"text": "Step 7: Then run the below command to install Ruby:"
},
{
"code": null,
"e": 27370,
"s": 27351,
"text": "$ pkg install ruby"
},
{
"code": null,
"e": 27407,
"s": 27370,
"text": "Step 8: Now enter “Y” when prompted:"
},
{
"code": null,
"e": 27455,
"s": 27407,
"text": "Step 9: Then we have to run the following link:"
},
{
"code": null,
"e": 27532,
"s": 27455,
"text": "echo \"export LD_LIBRARY_PATH=/data/data/com.termux/files/usr/lib\">>-/.bashrc"
},
{
"code": null,
"e": 27601,
"s": 27532,
"text": "Step 10: Then we have to run the below command to exit from termux:"
},
{
"code": null,
"e": 27608,
"s": 27601,
"text": "$ exit"
},
{
"code": null,
"e": 27673,
"s": 27608,
"text": "Use the below command to verify the Ruby installation on Termux:"
},
{
"code": null,
"e": 27690,
"s": 27673,
"text": "$ ruby\n$ ruby -v"
},
{
"code": null,
"e": 27769,
"s": 27690,
"text": "Congratulation. At this point, you have successfully installed Ruby on Termux."
},
{
"code": null,
"e": 27783,
"s": 27769,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27798,
"s": 27783,
"text": "how-to-install"
},
{
"code": null,
"e": 27805,
"s": 27798,
"text": "Picked"
},
{
"code": null,
"e": 27812,
"s": 27805,
"text": "How To"
},
{
"code": null,
"e": 27831,
"s": 27812,
"text": "Installation Guide"
},
{
"code": null,
"e": 27929,
"s": 27831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27963,
"s": 27929,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28021,
"s": 27963,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28070,
"s": 28021,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28117,
"s": 28070,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 28159,
"s": 28117,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28192,
"s": 28159,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28226,
"s": 28192,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28261,
"s": 28226,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28319,
"s": 28261,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
]
|
Python | Check for float string - GeeksforGeeks | 29 May, 2019
One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let’s discuss certain ways in which one can check if string is a float to avoid potential errors.
Method #1 : Using isdigit() + replace()The combination of above function is used to perform this task and hence. This works in 2 steps, first the point value is erased and the string is joined to form a digit and then is checked. The drawback is that this doesn’t check for potential exponent values that can also form a float number.
# Python3 code to demonstrate# Check for float string# using isdigit() + replace() # initializing string test_string = "45.657" # printing original string print("The original string : " + str(test_string)) # using isdigit() + replace()# Check for float stringres = test_string.replace('.', '', 1).isdigit() # print resultprint("Is string a possible float number ? : " + str(res))
The original string : 45.657
Is string a possible float number ? : True
Method #2 : Using float() + Exception handlingThis task can also be achieved using the float function which tries to convert the string to floating point value, and it’s failure guarantees that it’s not potential float value.
# Python3 code to demonstrate# Check for float string# using float() # initializing string test_string = "45.657" # printing original string print("The original string : " + str(test_string)) # using float()# Check for float stringtry : float(test_string) res = Trueexcept : print("Not a float") res = False # print resultprint("Is string a possible float number ? : " + str(res))
The original string : 45.657
Is string a possible float number ? : True
Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 26424,
"s": 26053,
"text": "One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let’s discuss certain ways in which one can check if string is a float to avoid potential errors."
},
{
"code": null,
"e": 26759,
"s": 26424,
"text": "Method #1 : Using isdigit() + replace()The combination of above function is used to perform this task and hence. This works in 2 steps, first the point value is erased and the string is joined to form a digit and then is checked. The drawback is that this doesn’t check for potential exponent values that can also form a float number."
},
{
"code": "# Python3 code to demonstrate# Check for float string# using isdigit() + replace() # initializing string test_string = \"45.657\" # printing original string print(\"The original string : \" + str(test_string)) # using isdigit() + replace()# Check for float stringres = test_string.replace('.', '', 1).isdigit() # print resultprint(\"Is string a possible float number ? : \" + str(res))",
"e": 27143,
"s": 26759,
"text": null
},
{
"code": null,
"e": 27216,
"s": 27143,
"text": "The original string : 45.657\nIs string a possible float number ? : True\n"
},
{
"code": null,
"e": 27444,
"s": 27218,
"text": "Method #2 : Using float() + Exception handlingThis task can also be achieved using the float function which tries to convert the string to floating point value, and it’s failure guarantees that it’s not potential float value."
},
{
"code": "# Python3 code to demonstrate# Check for float string# using float() # initializing string test_string = \"45.657\" # printing original string print(\"The original string : \" + str(test_string)) # using float()# Check for float stringtry : float(test_string) res = Trueexcept : print(\"Not a float\") res = False # print resultprint(\"Is string a possible float number ? : \" + str(res))",
"e": 27846,
"s": 27444,
"text": null
},
{
"code": null,
"e": 27919,
"s": 27846,
"text": "The original string : 45.657\nIs string a possible float number ? : True\n"
},
{
"code": null,
"e": 27942,
"s": 27919,
"text": "Python string-programs"
},
{
"code": null,
"e": 27949,
"s": 27942,
"text": "Python"
},
{
"code": null,
"e": 28047,
"s": 27949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28065,
"s": 28047,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28097,
"s": 28065,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28119,
"s": 28097,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28161,
"s": 28119,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28191,
"s": 28161,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28217,
"s": 28191,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28261,
"s": 28217,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28290,
"s": 28261,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28326,
"s": 28290,
"text": "Convert integer to string in Python"
}
]
|
Maximize sum of values in total K steps starting at position M - GeeksforGeeks | 17 Jan, 2022
Given a sorted array arr[] containing N pairs [A, B], wherer A is the position in X axis and B is the value on that position. All the positions are distinct. The array is sorted in increasing order of position. Given two integers M and K. The task is to maximize the sum of values that can be visited starting from the position M and taking total K steps where:
One can move to right or left by 1 position (from x to x+1 or x-1) by taking 1 step.
The value of any position can be added to the final sum only once.
There is no movement along the Y axis.
Examples:
Input: arr[][] = {{2, 8}, {6, 3}, {8, 6}}, M = 5, K = 4Output: 9Explanation: The optimal way is to:Move right to position 6 and add 3. Movement 1 position. Move right to position 8 and add 6. Movement 2 position.Total movement 3 steps and sum = 3 + 6 = 9.
Input: arr[][] = {{1, 7}, {3, 6}, {4, 5}, {6, 5}}, M = 3, K = 4Output: 18Explanation: The optimal way of movement is:Add value at position 3 to answer.Move right to position 4 and add 5.Move left to position 1 and add 7.Total sum = 6 + 5 + 7 = 18.Notice that position 3 can be visited twice but value is added only once.
Input: arr[][] = {{0, 3}, {6, 4}, {8, 5}}, M = 3, K = 2Output: 0Explanation: Movement can be most K = 2 positions and cannot reach any position with points .
Approach: The approach is based on the concept of prefix sum. The range which can be covered standing at any position that needs to be determined at then the total points can be calculated from prefix sum array. Follow the steps below:
Find the Prefix Sum for the maximum possible position. After that, perform two loops.
The first loop will be when travelling to the right first and then to the left is considered.
The second loop will occur when moving to the left first, then to the right is considered.
The maximum number of Seeds covered in all feasible ranges is the final answer.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to calculate maximum points// that can be collectedint maxTotalPoints(vector<vector<int> >& arr, int M, int K){ int MX = 2e5 + 2; int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; vector<int> prefix_sum(MX); for (auto& it : arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = min(M, M - (K - 2 * (r - M))); l = max(1, l); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = max(M, M + (K - 2 * (M - l))); r = min(MX - 1, r); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans;} // Driver codeint main(){ vector<vector<int>> arr{{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; cout<<maxTotalPoints(arr, M, K); return 0;}
// Java code to implement above approachimport java.util.*;class GFG{ // Function to calculate maximum points // that can be collected static int maxTotalPoints(int[][] arr, int M, int K) { int MX = (int) (2e5 + 2); int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; int []prefix_sum = new int[MX]; for (int []it : arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.min(M, M - (K - 2 * (r - M))); l = Math.max(1, l); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.max(M, M + (K - 2 * (M - l))); r = Math.min(MX - 1, r); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code public static void main(String[] args) { int [][]arr = {{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; System.out.print(maxTotalPoints(arr, M, K)); }} // This code is contributed by 29AjayKumar
# Python code to implement above approach # Function to calculate maximum points# that can be collecteddef maxTotalPoints(arr, M, K): MX = (int)(2e5 + 2); i, l, r, ans = 0, 0, 0, 0; # Incremented positions by one # to make calculations easier. M += 1; prefix_sum = [0 for i in range(MX)]; for it in arr: prefix_sum[it[0] + 1] = it[1]; for i in range(MX): prefix_sum[i] += prefix_sum[i - 1]; for r in range(M, (M + K + 1) and ( r < MX and r <= M + K)): l = min(M, M - (K - 2 * (r - M))); l = max(1, l); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); for l in range(M, (M - K - 1) and l > 0, -1): r = max(M, M + (K - 2 * (M - l))); r = min(MX - 1, r); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); return ans; # Driver codeif __name__ == '__main__': arr = [[2, 8], [6, 3], [8, 6]]; M = 5; K = 4; print(maxTotalPoints(arr, M, K)); # This code is contributed by 29AjayKumar
// C# code to implement above approachusing System;class GFG{ // Function to calculate maximum points // that can be collected static int maxTotalPoints(int[,] arr, int M, int K) { int MX = (int) (2e5 + 2); int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; int []prefix_sum = new int[MX]; for (int it = 0; it < arr.GetLength(0); it++) { prefix_sum[arr[it, 0] + 1] = arr[it, 1]; } for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.Min(M, M - (K - 2 * (r - M))); l = Math.Max(1, l); ans = Math.Max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.Max(M, M + (K - 2 * (M - l))); r = Math.Min(MX - 1, r); ans = Math.Max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code public static void Main() { int [,]arr = {{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; Console.Write(maxTotalPoints(arr, M, K)); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach // Function to calculate maximum points // that can be collected function maxTotalPoints(arr, M, K) { let MX = 2e5 + 2; let i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; let prefix_sum = new Array(MX).fill(0); for (let it of arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.min(M, M - (K - 2 * (r - M))); l = Math.max(1, l); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.max(M, M + (K - 2 * (M - l))); r = Math.min(MX - 1, r); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code let arr = [[2, 8], [6, 3], [8, 6]]; let M = 5; let K = 4; document.write(maxTotalPoints(arr, M, K)); // This code is contributed by Potta Lokesh </script>
9
Time Complexity: O(X), where X is the maximum positionAuxiliary Space: O(X)
lokeshpotta20
29AjayKumar
samim2000
Algo-Geek 2021
prefix-sum
Algo Geek
Arrays
Greedy
Mathematical
prefix-sum
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Count of Palindrome Strings in given Array of strings
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation | [
{
"code": null,
"e": 27509,
"s": 27481,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 27871,
"s": 27509,
"text": "Given a sorted array arr[] containing N pairs [A, B], wherer A is the position in X axis and B is the value on that position. All the positions are distinct. The array is sorted in increasing order of position. Given two integers M and K. The task is to maximize the sum of values that can be visited starting from the position M and taking total K steps where:"
},
{
"code": null,
"e": 27956,
"s": 27871,
"text": "One can move to right or left by 1 position (from x to x+1 or x-1) by taking 1 step."
},
{
"code": null,
"e": 28023,
"s": 27956,
"text": "The value of any position can be added to the final sum only once."
},
{
"code": null,
"e": 28062,
"s": 28023,
"text": "There is no movement along the Y axis."
},
{
"code": null,
"e": 28072,
"s": 28062,
"text": "Examples:"
},
{
"code": null,
"e": 28329,
"s": 28072,
"text": "Input: arr[][] = {{2, 8}, {6, 3}, {8, 6}}, M = 5, K = 4Output: 9Explanation: The optimal way is to:Move right to position 6 and add 3. Movement 1 position. Move right to position 8 and add 6. Movement 2 position.Total movement 3 steps and sum = 3 + 6 = 9."
},
{
"code": null,
"e": 28650,
"s": 28329,
"text": "Input: arr[][] = {{1, 7}, {3, 6}, {4, 5}, {6, 5}}, M = 3, K = 4Output: 18Explanation: The optimal way of movement is:Add value at position 3 to answer.Move right to position 4 and add 5.Move left to position 1 and add 7.Total sum = 6 + 5 + 7 = 18.Notice that position 3 can be visited twice but value is added only once."
},
{
"code": null,
"e": 28808,
"s": 28650,
"text": "Input: arr[][] = {{0, 3}, {6, 4}, {8, 5}}, M = 3, K = 2Output: 0Explanation: Movement can be most K = 2 positions and cannot reach any position with points ."
},
{
"code": null,
"e": 29044,
"s": 28808,
"text": "Approach: The approach is based on the concept of prefix sum. The range which can be covered standing at any position that needs to be determined at then the total points can be calculated from prefix sum array. Follow the steps below:"
},
{
"code": null,
"e": 29130,
"s": 29044,
"text": "Find the Prefix Sum for the maximum possible position. After that, perform two loops."
},
{
"code": null,
"e": 29224,
"s": 29130,
"text": "The first loop will be when travelling to the right first and then to the left is considered."
},
{
"code": null,
"e": 29315,
"s": 29224,
"text": "The second loop will occur when moving to the left first, then to the right is considered."
},
{
"code": null,
"e": 29395,
"s": 29315,
"text": "The maximum number of Seeds covered in all feasible ranges is the final answer."
},
{
"code": null,
"e": 29445,
"s": 29395,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 29449,
"s": 29445,
"text": "C++"
},
{
"code": null,
"e": 29454,
"s": 29449,
"text": "Java"
},
{
"code": null,
"e": 29462,
"s": 29454,
"text": "Python3"
},
{
"code": null,
"e": 29465,
"s": 29462,
"text": "C#"
},
{
"code": null,
"e": 29476,
"s": 29465,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to calculate maximum points// that can be collectedint maxTotalPoints(vector<vector<int> >& arr, int M, int K){ int MX = 2e5 + 2; int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; vector<int> prefix_sum(MX); for (auto& it : arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = min(M, M - (K - 2 * (r - M))); l = max(1, l); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = max(M, M + (K - 2 * (M - l))); r = min(MX - 1, r); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans;} // Driver codeint main(){ vector<vector<int>> arr{{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; cout<<maxTotalPoints(arr, M, K); return 0;}",
"e": 30549,
"s": 29476,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*;class GFG{ // Function to calculate maximum points // that can be collected static int maxTotalPoints(int[][] arr, int M, int K) { int MX = (int) (2e5 + 2); int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; int []prefix_sum = new int[MX]; for (int []it : arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.min(M, M - (K - 2 * (r - M))); l = Math.max(1, l); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.max(M, M + (K - 2 * (M - l))); r = Math.min(MX - 1, r); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code public static void main(String[] args) { int [][]arr = {{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; System.out.print(maxTotalPoints(arr, M, K)); }} // This code is contributed by 29AjayKumar",
"e": 31718,
"s": 30549,
"text": null
},
{
"code": "# Python code to implement above approach # Function to calculate maximum points# that can be collecteddef maxTotalPoints(arr, M, K): MX = (int)(2e5 + 2); i, l, r, ans = 0, 0, 0, 0; # Incremented positions by one # to make calculations easier. M += 1; prefix_sum = [0 for i in range(MX)]; for it in arr: prefix_sum[it[0] + 1] = it[1]; for i in range(MX): prefix_sum[i] += prefix_sum[i - 1]; for r in range(M, (M + K + 1) and ( r < MX and r <= M + K)): l = min(M, M - (K - 2 * (r - M))); l = max(1, l); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); for l in range(M, (M - K - 1) and l > 0, -1): r = max(M, M + (K - 2 * (M - l))); r = min(MX - 1, r); ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]); return ans; # Driver codeif __name__ == '__main__': arr = [[2, 8], [6, 3], [8, 6]]; M = 5; K = 4; print(maxTotalPoints(arr, M, K)); # This code is contributed by 29AjayKumar",
"e": 32706,
"s": 31718,
"text": null
},
{
"code": "// C# code to implement above approachusing System;class GFG{ // Function to calculate maximum points // that can be collected static int maxTotalPoints(int[,] arr, int M, int K) { int MX = (int) (2e5 + 2); int i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; int []prefix_sum = new int[MX]; for (int it = 0; it < arr.GetLength(0); it++) { prefix_sum[arr[it, 0] + 1] = arr[it, 1]; } for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.Min(M, M - (K - 2 * (r - M))); l = Math.Max(1, l); ans = Math.Max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.Max(M, M + (K - 2 * (M - l))); r = Math.Min(MX - 1, r); ans = Math.Max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code public static void Main() { int [,]arr = {{2, 8}, {6, 3}, {8, 6}}; int M = 5; int K = 4; Console.Write(maxTotalPoints(arr, M, K)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 33913,
"s": 32706,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to calculate maximum points // that can be collected function maxTotalPoints(arr, M, K) { let MX = 2e5 + 2; let i, l, r, ans = 0; // Incremented positions by one // to make calculations easier. M++; let prefix_sum = new Array(MX).fill(0); for (let it of arr) prefix_sum[it[0] + 1] = it[1]; for (i = 1; i < MX; i++) prefix_sum[i] += prefix_sum[i - 1]; for (r = M; r < MX && r <= M + K; r++) { l = Math.min(M, M - (K - 2 * (r - M))); l = Math.max(1, l); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } for (l = M; l > 0 && l >= M - K; l--) { r = Math.max(M, M + (K - 2 * (M - l))); r = Math.min(MX - 1, r); ans = Math.max(ans, prefix_sum[r] - prefix_sum[l - 1]); } return ans; } // Driver code let arr = [[2, 8], [6, 3], [8, 6]]; let M = 5; let K = 4; document.write(maxTotalPoints(arr, M, K)); // This code is contributed by Potta Lokesh </script>",
"e": 35185,
"s": 33913,
"text": null
},
{
"code": null,
"e": 35190,
"s": 35188,
"text": "9"
},
{
"code": null,
"e": 35268,
"s": 35192,
"text": "Time Complexity: O(X), where X is the maximum positionAuxiliary Space: O(X)"
},
{
"code": null,
"e": 35284,
"s": 35270,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 35296,
"s": 35284,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35306,
"s": 35296,
"text": "samim2000"
},
{
"code": null,
"e": 35321,
"s": 35306,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 35332,
"s": 35321,
"text": "prefix-sum"
},
{
"code": null,
"e": 35342,
"s": 35332,
"text": "Algo Geek"
},
{
"code": null,
"e": 35349,
"s": 35342,
"text": "Arrays"
},
{
"code": null,
"e": 35356,
"s": 35349,
"text": "Greedy"
},
{
"code": null,
"e": 35369,
"s": 35356,
"text": "Mathematical"
},
{
"code": null,
"e": 35380,
"s": 35369,
"text": "prefix-sum"
},
{
"code": null,
"e": 35387,
"s": 35380,
"text": "Arrays"
},
{
"code": null,
"e": 35394,
"s": 35387,
"text": "Greedy"
},
{
"code": null,
"e": 35407,
"s": 35394,
"text": "Mathematical"
},
{
"code": null,
"e": 35505,
"s": 35407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35560,
"s": 35505,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 35608,
"s": 35560,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 35648,
"s": 35608,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 35728,
"s": 35648,
"text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64"
},
{
"code": null,
"e": 35782,
"s": 35728,
"text": "Count of Palindrome Strings in given Array of strings"
},
{
"code": null,
"e": 35797,
"s": 35782,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35813,
"s": 35797,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35881,
"s": 35813,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35927,
"s": 35881,
"text": "Write a program to reverse an array or string"
}
]
|
Python program to count the number of spaces in string - GeeksforGeeks | 12 Jul, 2021
Given a string, the task is to write a Python program to count the number of spaces in the string.
Examples:
Input: "my name is geeks for geeks"
Output: number of spaces = 5
Input: "geeksforgeeks"
Output: number of spaces=0
Approach:
Input string from the user
Initialize count variable with zero
Run a for loop i from 0 till the length of the string
Inside for loop, check if s[i] == blank, then increment count by 1
Outside for loop, print count
Example 1:
Python3
# create function that# return space countdef check_space(string): # counter count = 0 # loop for search each index for i in range(0, len(string)): # Check each char # is blank or not if string[i] == " ": count += 1 return count # driver nodestring = "Welcome to geeksforgeeks" # call the function and displayprint("number of spaces ",check_space(string))
Output:
number of spaces 2
Example 2:
Python3
# create function that# return space countdef check_space(string): # counter count = 0 # loop for search each index for i in string: # Check each char # is blank or not if i == " ": count += 1 return count # driver nodestring = "Welcome to geeksforgeeks, Geeks!" # call the function and displayprint("number of spaces ",check_space(string))
Output:
number of spaces 3
Example 3: Using the count() function.
Python3
# Create function that# return space countdef check_space(Test_string): return Test_string.count(" ") # Driver functionif __name__ == "__main__": Test_string = "Welcome to geeksforgeeks, Geeks!" # Call the function and display print(f"Number of Spaces: {check_space(Test_string)}")
Output:
Number of Spaces: 3
gittysatyam
pradiptamukherjee
ruhelaa48
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 25636,
"s": 25537,
"text": "Given a string, the task is to write a Python program to count the number of spaces in the string."
},
{
"code": null,
"e": 25646,
"s": 25636,
"text": "Examples:"
},
{
"code": null,
"e": 25762,
"s": 25646,
"text": "Input: \"my name is geeks for geeks\"\nOutput: number of spaces = 5\n\nInput: \"geeksforgeeks\"\nOutput: number of spaces=0"
},
{
"code": null,
"e": 25772,
"s": 25762,
"text": "Approach:"
},
{
"code": null,
"e": 25799,
"s": 25772,
"text": "Input string from the user"
},
{
"code": null,
"e": 25835,
"s": 25799,
"text": "Initialize count variable with zero"
},
{
"code": null,
"e": 25889,
"s": 25835,
"text": "Run a for loop i from 0 till the length of the string"
},
{
"code": null,
"e": 25956,
"s": 25889,
"text": "Inside for loop, check if s[i] == blank, then increment count by 1"
},
{
"code": null,
"e": 25986,
"s": 25956,
"text": "Outside for loop, print count"
},
{
"code": null,
"e": 25997,
"s": 25986,
"text": "Example 1:"
},
{
"code": null,
"e": 26005,
"s": 25997,
"text": "Python3"
},
{
"code": "# create function that# return space countdef check_space(string): # counter count = 0 # loop for search each index for i in range(0, len(string)): # Check each char # is blank or not if string[i] == \" \": count += 1 return count # driver nodestring = \"Welcome to geeksforgeeks\" # call the function and displayprint(\"number of spaces \",check_space(string))",
"e": 26436,
"s": 26005,
"text": null
},
{
"code": null,
"e": 26444,
"s": 26436,
"text": "Output:"
},
{
"code": null,
"e": 26464,
"s": 26444,
"text": "number of spaces 2"
},
{
"code": null,
"e": 26475,
"s": 26464,
"text": "Example 2:"
},
{
"code": null,
"e": 26483,
"s": 26475,
"text": "Python3"
},
{
"code": "# create function that# return space countdef check_space(string): # counter count = 0 # loop for search each index for i in string: # Check each char # is blank or not if i == \" \": count += 1 return count # driver nodestring = \"Welcome to geeksforgeeks, Geeks!\" # call the function and displayprint(\"number of spaces \",check_space(string)) ",
"e": 26903,
"s": 26483,
"text": null
},
{
"code": null,
"e": 26911,
"s": 26903,
"text": "Output:"
},
{
"code": null,
"e": 26931,
"s": 26911,
"text": "number of spaces 3"
},
{
"code": null,
"e": 26970,
"s": 26931,
"text": "Example 3: Using the count() function."
},
{
"code": null,
"e": 26978,
"s": 26970,
"text": "Python3"
},
{
"code": "# Create function that# return space countdef check_space(Test_string): return Test_string.count(\" \") # Driver functionif __name__ == \"__main__\": Test_string = \"Welcome to geeksforgeeks, Geeks!\" # Call the function and display print(f\"Number of Spaces: {check_space(Test_string)}\")",
"e": 27274,
"s": 26978,
"text": null
},
{
"code": null,
"e": 27283,
"s": 27274,
"text": "Output: "
},
{
"code": null,
"e": 27303,
"s": 27283,
"text": "Number of Spaces: 3"
},
{
"code": null,
"e": 27315,
"s": 27303,
"text": "gittysatyam"
},
{
"code": null,
"e": 27333,
"s": 27315,
"text": "pradiptamukherjee"
},
{
"code": null,
"e": 27343,
"s": 27333,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27366,
"s": 27343,
"text": "Python string-programs"
},
{
"code": null,
"e": 27390,
"s": 27366,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "Python"
},
{
"code": null,
"e": 27413,
"s": 27397,
"text": "Python Programs"
},
{
"code": null,
"e": 27432,
"s": 27413,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27530,
"s": 27432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27562,
"s": 27530,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27604,
"s": 27562,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27646,
"s": 27604,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27673,
"s": 27646,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27729,
"s": 27673,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27751,
"s": 27729,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27790,
"s": 27751,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27836,
"s": 27790,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27874,
"s": 27836,
"text": "Python | Convert a list to dictionary"
}
]
|
PHP | Check if all characters are lower case - GeeksforGeeks | 30 Sep, 2021
Given a string, check if all characters of it are in lowercase.Examples:
Input : gfg123
Output : No
Explanation : There are characters
'1', '2' and '3' that are not lower-
case
Input : geeksforgeeks
Output : Yes
Explanation : The string "geeksforgeeks"
consists of all lowercase letters.
The above problem can be solved using the in-built functions in PHP. We store multiple values in an array and check using the in-built function in php to check whether all the characters are lowercase.
We solve the given problem using the in-built functions in PHP and iterate from a given array of strings.We use the following in-built function in PHP:
ctype_lower : Returns true if all of the characters in the provided string, text, are lowercase letters. Otherwise returns false.
PHP
<?php// PHP program to check if a string has all// lower case characters $strings = array('gfg123', 'geeksforgeeks', 'GfG'); // Checking for above three strings one by one.foreach ($strings as $testcase) { if (ctype_lower($testcase)) { echo "Yes\n"; } else { echo "No\n"; }}?>
Output :
No
Yes
No
adnanirshad158
PHP-function
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
Different ways for passing data to view in Laravel
How to pass form variables from one page to other page in PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26241,
"s": 26213,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26316,
"s": 26241,
"text": "Given a string, check if all characters of it are in lowercase.Examples: "
},
{
"code": null,
"e": 26535,
"s": 26316,
"text": "Input : gfg123\nOutput : No\nExplanation : There are characters\n'1', '2' and '3' that are not lower-\ncase\n\nInput : geeksforgeeks\nOutput : Yes\nExplanation : The string \"geeksforgeeks\" \nconsists of all lowercase letters."
},
{
"code": null,
"e": 26740,
"s": 26537,
"text": "The above problem can be solved using the in-built functions in PHP. We store multiple values in an array and check using the in-built function in php to check whether all the characters are lowercase. "
},
{
"code": null,
"e": 26893,
"s": 26740,
"text": "We solve the given problem using the in-built functions in PHP and iterate from a given array of strings.We use the following in-built function in PHP: "
},
{
"code": null,
"e": 27023,
"s": 26893,
"text": "ctype_lower : Returns true if all of the characters in the provided string, text, are lowercase letters. Otherwise returns false."
},
{
"code": null,
"e": 27027,
"s": 27023,
"text": "PHP"
},
{
"code": "<?php// PHP program to check if a string has all// lower case characters $strings = array('gfg123', 'geeksforgeeks', 'GfG'); // Checking for above three strings one by one.foreach ($strings as $testcase) { if (ctype_lower($testcase)) { echo \"Yes\\n\"; } else { echo \"No\\n\"; }}?>",
"e": 27327,
"s": 27027,
"text": null
},
{
"code": null,
"e": 27337,
"s": 27327,
"text": "Output : "
},
{
"code": null,
"e": 27347,
"s": 27337,
"text": "No\nYes\nNo"
},
{
"code": null,
"e": 27362,
"s": 27347,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27375,
"s": 27362,
"text": "PHP-function"
},
{
"code": null,
"e": 27386,
"s": 27375,
"text": "PHP-string"
},
{
"code": null,
"e": 27390,
"s": 27386,
"text": "PHP"
},
{
"code": null,
"e": 27407,
"s": 27390,
"text": "Web Technologies"
},
{
"code": null,
"e": 27411,
"s": 27407,
"text": "PHP"
},
{
"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": 27591,
"s": 27509,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27633,
"s": 27591,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27660,
"s": 27633,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 27711,
"s": 27660,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27775,
"s": 27711,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 27815,
"s": 27775,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27848,
"s": 27815,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27893,
"s": 27848,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27936,
"s": 27893,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
numpy.ndarray.byteswap() in Python - GeeksforGeeks | 28 Nov, 2018
numpy.ndarray.byteswap() function toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place.
Syntax: ndarray.byteswap(inplace=False)
Parameters:inplace : [bool, optional] If True, swap bytes in-place, default is False.
Returns:out : [ndarray] The byteswapped array. If inplace is True, this is a view to self.
Code #1:
# Python program explaining # byteswap() function import numpy as geek # a is an array of integers.a = geek.array([1, 256, 100], dtype = np.int16) print(a.byteswap(True))
Output :
[256 1 25600]
Code #2: byteswap() function does not work on arrays of strings.
# Python program explaining # byteswap() function import numpy as geek # a is an array of stringsa = geek.array(["arka","soumen","simran"],dtype = np.int16) print(a.byteswap(True))
Output :
ValueError Traceback (most recent call last)
in ()
1 import numpy as geek
----> 2 a = geek.array(["arka","soumen","simran"],dtype = np.int16)
3
4 #a is an array of strings
5
ValueError: invalid literal for int() with base 10: 'arka'
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 25695,
"s": 25537,
"text": "numpy.ndarray.byteswap() function toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place."
},
{
"code": null,
"e": 25735,
"s": 25695,
"text": "Syntax: ndarray.byteswap(inplace=False)"
},
{
"code": null,
"e": 25821,
"s": 25735,
"text": "Parameters:inplace : [bool, optional] If True, swap bytes in-place, default is False."
},
{
"code": null,
"e": 25912,
"s": 25821,
"text": "Returns:out : [ndarray] The byteswapped array. If inplace is True, this is a view to self."
},
{
"code": null,
"e": 25921,
"s": 25912,
"text": "Code #1:"
},
{
"code": "# Python program explaining # byteswap() function import numpy as geek # a is an array of integers.a = geek.array([1, 256, 100], dtype = np.int16) print(a.byteswap(True))",
"e": 26095,
"s": 25921,
"text": null
},
{
"code": null,
"e": 26104,
"s": 26095,
"text": "Output :"
},
{
"code": null,
"e": 26120,
"s": 26104,
"text": "[256 1 25600]"
},
{
"code": null,
"e": 26187,
"s": 26122,
"text": "Code #2: byteswap() function does not work on arrays of strings."
},
{
"code": "# Python program explaining # byteswap() function import numpy as geek # a is an array of stringsa = geek.array([\"arka\",\"soumen\",\"simran\"],dtype = np.int16) print(a.byteswap(True))",
"e": 26370,
"s": 26187,
"text": null
},
{
"code": null,
"e": 26379,
"s": 26370,
"text": "Output :"
},
{
"code": null,
"e": 26671,
"s": 26379,
"text": "ValueError Traceback (most recent call last)\n in ()\n 1 import numpy as geek\n----> 2 a = geek.array([\"arka\",\"soumen\",\"simran\"],dtype = np.int16)\n 3 \n 4 #a is an array of strings\n 5 \n\nValueError: invalid literal for int() with base 10: 'arka'"
},
{
"code": null,
"e": 26692,
"s": 26671,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 26705,
"s": 26692,
"text": "Python-numpy"
},
{
"code": null,
"e": 26712,
"s": 26705,
"text": "Python"
},
{
"code": null,
"e": 26810,
"s": 26712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26842,
"s": 26810,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26884,
"s": 26842,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26926,
"s": 26884,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26953,
"s": 26926,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27009,
"s": 26953,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27031,
"s": 27009,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27070,
"s": 27031,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27101,
"s": 27070,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27130,
"s": 27101,
"text": "Create a directory in Python"
}
]
|
How to save an image to localStorage and display it on the next page? - GeeksforGeeks | 14 Dec, 2020
What is localStorage?
The localStorage is a Web API available to all modern web browsers by default. It allows websites to store a minimal amount of data in the browser which can be used in future browser sessions. localStorage is similar to sessionStorage except that the localStorage does not have an expiration date.
Advantages of localStorage
Can store a large amount of data compared to cookie-based storage of data (typically 2MB – 10MB)
Data persists in the browser to be used across future browser sessions as long as the same protocol on the domain is being used.
Data need not be passed with each req and res objects.
Why localStorage?
Experiment with a fake back end when the network connection is poor.
Saving some default data across sessions like form data ( first name, address, etc) when it needs to be filled multiple times.
Syntax:
window.localStorage // It returns a Storage Object
Methods of localStorage:
setItem(key, value): Used to save data to localStorage.removeItem(key): Used to remove data from localStorage.getItem(key): It read data from localStorage.clear(): It clears localStorage (on the domain).
setItem(key, value): Used to save data to localStorage.
removeItem(key): Used to remove data from localStorage.
getItem(key): It read data from localStorage.
clear(): It clears localStorage (on the domain).
Syntax to save data to localStorage:
localStorage.setItem(key, value)
Ex: localStorage.setItem("firstName", "Mark Zuker berg");
Syntax to read data from localStorage:
localStorage.getItem(key)
// Returns the string "Mark Zuker berg"
Ex: localStorage.getItem("firstName");
Syntax to remove data from localStorage:
localStorage.removeItem(key)
Ex: localStorage.removeItem("firstName");
We have learned the required basics about localStorage. Let’s implement the above methods with an example.
Prerequisites:
Basic knowledge of React.Any code Editor.
Basic knowledge of React.
Any code Editor.
Example: We will implement a small image posting platform called Pics Villa, with two web pages:
1. Post form: Takes the input from the user. It takes the following input:
Post Title: The title for our post and is of string type.
Image URL: URL of the image. It can be the public link of the image stored in Google cloud or any other service of your choice. However, for this example, all the images are uploaded to Github and the link to download is used. In this case, the image url may look something like the following format: https://raw.githubusercontent.com/<your username>/<your repo name>/<actual-image-path>
Post Comment: It is a multi-line string.
2. All Posts: Displays the form data entered by the User.
Steps to create your application:
1. Create your application using the following command:
npx create-react-app crud-application
2. The above command creates a React project for us with all the required boilerplate. Let’s enter into the src folder of the project by typing the below command:
cd crud-application/src
3. You can remove some unnecessary files (Optional step):
rm App.css App.test.js logo.svg
4. To allow routing of web pages. Install the following module:
npm i react-router-dom
5. Check your package.json to match the following dependencies:
"dependencies": {
.......................
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4",
.....................
// Other dependencies (if any)
},
Filename: App.js
Javascript
import React, { Component } from 'react';import { BrowserRouter, Route, Switch } from 'react-router-dom';import PostForm from './PostForm';import AllPost from './AllPost'; class App extends Component { render() { return ( <div className="App"> <BrowserRouter> <Switch> <Route exact path ='/' render= {props => <PostForm {...props} />}> </Route> <Route exact path='/gallery' render= {props => <AllPost {...props} />}> </Route> </Switch> </BrowserRouter> </div> ); } }export default App;
Filename: Index.js
Javascript
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App'; ReactDOM.render(<App /> , document.getElementById('root'));
Filename: PostForm.js
Javascript
import React, { Component } from 'react';import { Link } from 'react-router-dom'; const galleryStyle ={ border: 'none', margin: 0, color: '#fff', fontWeight: 'bold', padding: '16px 20px', position: 'absolute', top: '35px', right: '200px', background: '#7bc74d',}const postBtnStyle = { border: 'none', margin: 0, color: '#fff', fontWeight: 'bold', padding: '16px 20px', background: '#7D4C92 ', width: '417px',}const parentDiv = { align: 'center', margin: '0px auto auto auto', textAlign: 'center',}const formStyle = { width: '400px', border: '1px solid lightgray', margin: '10px auto 10px auto', textAlign: 'center', padding: '30px 40px 30px 40px',}const inputFields = { width: 'inherit', fontFamily: 'arial', padding: '6px',} class PostForm extends Component { handleSubmit = (e) => { e.preventDefault(); const title = this.getTitle.value; const message = this.getMessage.value; const image = this.getImage.value; localStorage.setItem('title', title); localStorage.setItem('message', message); localStorage.setItem('image', image); this.getTitle.value=''; this.getMessage.value = ''; this.getImage.value = ''; }render() { return ( <div style={parentDiv}> <h1 style={{color:'#8A2482'}}>Pics <span style={{color:'#248A6E'}}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h3>Create a new Post</h3> <form onSubmit={this.handleSubmit} style={formStyle}> <input style={inputFields} required type="text" placeholder="Enter Post Title" ref={(input)=> this.getTitle = input } /><br /><br /> <input style={inputFields} required type="text" placeholder="Paste your image url here" ref={(input) => this.getImage = input} /><br></br> <br></br> <textarea style={inputFields} required rows="5" cols="28" placeholder="Enter Comment" ref={(input)=>this.getMessage = input}/> <br /><br /> <button style={postBtnStyle}>Post</button> </form> <Link to='/gallery'> <button style={galleryStyle}> View Gallery </button> </Link> </div> );}}export default PostForm;
Filename: AllPost.js
Javascript
import React, { Component } from 'react';import Post from './Post'; const parentDiv = { align: 'center', margin: '0px auto auto auto', textAlign: 'center',} class AllPost extends Component { render() { return ( <div style={parentDiv}> <h1 style={{color:'#8A2482'}}>Pics <span style={{color: '#248A6E'}}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h1>All Posts</h1> <Post/> </div> ); }} export default AllPost;
Filename: Post.js
Javascript
import React, { Component } from 'react'; class Post extends Component { render() { return ( <div style={{ width: '50%', margin: '0px auto' }} > <h2>{localStorage.getItem('title')}</h2> <img src={localStorage.getItem('image')} alt={'C - language'} /> <p style={{width: '50%', margin: '0px auto'}} >{localStorage.getItem('message')}</p> </div> ); }}export default Post;
Run the application using the following command:
npm start
After the server is started, you will see the following output on your screen:
Enter some data into the form and click on View Gallery to see the uploaded image as below:
Picked
react-js
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 26567,
"s": 26545,
"text": "What is localStorage?"
},
{
"code": null,
"e": 26865,
"s": 26567,
"text": "The localStorage is a Web API available to all modern web browsers by default. It allows websites to store a minimal amount of data in the browser which can be used in future browser sessions. localStorage is similar to sessionStorage except that the localStorage does not have an expiration date."
},
{
"code": null,
"e": 26892,
"s": 26865,
"text": "Advantages of localStorage"
},
{
"code": null,
"e": 26989,
"s": 26892,
"text": "Can store a large amount of data compared to cookie-based storage of data (typically 2MB – 10MB)"
},
{
"code": null,
"e": 27118,
"s": 26989,
"text": "Data persists in the browser to be used across future browser sessions as long as the same protocol on the domain is being used."
},
{
"code": null,
"e": 27173,
"s": 27118,
"text": "Data need not be passed with each req and res objects."
},
{
"code": null,
"e": 27191,
"s": 27173,
"text": "Why localStorage?"
},
{
"code": null,
"e": 27260,
"s": 27191,
"text": "Experiment with a fake back end when the network connection is poor."
},
{
"code": null,
"e": 27387,
"s": 27260,
"text": "Saving some default data across sessions like form data ( first name, address, etc) when it needs to be filled multiple times."
},
{
"code": null,
"e": 27395,
"s": 27387,
"text": "Syntax:"
},
{
"code": null,
"e": 27448,
"s": 27395,
"text": "window.localStorage // It returns a Storage Object"
},
{
"code": null,
"e": 27473,
"s": 27448,
"text": "Methods of localStorage:"
},
{
"code": null,
"e": 27677,
"s": 27473,
"text": "setItem(key, value): Used to save data to localStorage.removeItem(key): Used to remove data from localStorage.getItem(key): It read data from localStorage.clear(): It clears localStorage (on the domain)."
},
{
"code": null,
"e": 27733,
"s": 27677,
"text": "setItem(key, value): Used to save data to localStorage."
},
{
"code": null,
"e": 27789,
"s": 27733,
"text": "removeItem(key): Used to remove data from localStorage."
},
{
"code": null,
"e": 27835,
"s": 27789,
"text": "getItem(key): It read data from localStorage."
},
{
"code": null,
"e": 27884,
"s": 27835,
"text": "clear(): It clears localStorage (on the domain)."
},
{
"code": null,
"e": 27921,
"s": 27884,
"text": "Syntax to save data to localStorage:"
},
{
"code": null,
"e": 28012,
"s": 27921,
"text": "localStorage.setItem(key, value)\nEx: localStorage.setItem(\"firstName\", \"Mark Zuker berg\");"
},
{
"code": null,
"e": 28051,
"s": 28012,
"text": "Syntax to read data from localStorage:"
},
{
"code": null,
"e": 28157,
"s": 28051,
"text": "localStorage.getItem(key)\n\n// Returns the string \"Mark Zuker berg\"\nEx: localStorage.getItem(\"firstName\");"
},
{
"code": null,
"e": 28198,
"s": 28157,
"text": "Syntax to remove data from localStorage:"
},
{
"code": null,
"e": 28269,
"s": 28198,
"text": "localStorage.removeItem(key)\nEx: localStorage.removeItem(\"firstName\");"
},
{
"code": null,
"e": 28376,
"s": 28269,
"text": "We have learned the required basics about localStorage. Let’s implement the above methods with an example."
},
{
"code": null,
"e": 28392,
"s": 28376,
"text": "Prerequisites: "
},
{
"code": null,
"e": 28434,
"s": 28392,
"text": "Basic knowledge of React.Any code Editor."
},
{
"code": null,
"e": 28460,
"s": 28434,
"text": "Basic knowledge of React."
},
{
"code": null,
"e": 28477,
"s": 28460,
"text": "Any code Editor."
},
{
"code": null,
"e": 28574,
"s": 28477,
"text": "Example: We will implement a small image posting platform called Pics Villa, with two web pages:"
},
{
"code": null,
"e": 28649,
"s": 28574,
"text": "1. Post form: Takes the input from the user. It takes the following input:"
},
{
"code": null,
"e": 28707,
"s": 28649,
"text": "Post Title: The title for our post and is of string type."
},
{
"code": null,
"e": 29095,
"s": 28707,
"text": "Image URL: URL of the image. It can be the public link of the image stored in Google cloud or any other service of your choice. However, for this example, all the images are uploaded to Github and the link to download is used. In this case, the image url may look something like the following format: https://raw.githubusercontent.com/<your username>/<your repo name>/<actual-image-path>"
},
{
"code": null,
"e": 29136,
"s": 29095,
"text": "Post Comment: It is a multi-line string."
},
{
"code": null,
"e": 29194,
"s": 29136,
"text": "2. All Posts: Displays the form data entered by the User."
},
{
"code": null,
"e": 29228,
"s": 29194,
"text": "Steps to create your application:"
},
{
"code": null,
"e": 29284,
"s": 29228,
"text": "1. Create your application using the following command:"
},
{
"code": null,
"e": 29322,
"s": 29284,
"text": "npx create-react-app crud-application"
},
{
"code": null,
"e": 29485,
"s": 29322,
"text": "2. The above command creates a React project for us with all the required boilerplate. Let’s enter into the src folder of the project by typing the below command:"
},
{
"code": null,
"e": 29509,
"s": 29485,
"text": "cd crud-application/src"
},
{
"code": null,
"e": 29567,
"s": 29509,
"text": "3. You can remove some unnecessary files (Optional step):"
},
{
"code": null,
"e": 29599,
"s": 29567,
"text": "rm App.css App.test.js logo.svg"
},
{
"code": null,
"e": 29663,
"s": 29599,
"text": "4. To allow routing of web pages. Install the following module:"
},
{
"code": null,
"e": 29686,
"s": 29663,
"text": "npm i react-router-dom"
},
{
"code": null,
"e": 29750,
"s": 29686,
"text": "5. Check your package.json to match the following dependencies:"
},
{
"code": null,
"e": 30006,
"s": 29750,
"text": "\"dependencies\": {\n .......................\n \"react\": \"^17.0.1\",\n \"react-dom\": \"^17.0.1\",\n \"react-router-dom\": \"^5.2.0\",\n \"react-scripts\": \"4.0.1\",\n \"web-vitals\": \"^0.2.4\",\n .....................\n // Other dependencies (if any)\n },"
},
{
"code": null,
"e": 30023,
"s": 30006,
"text": "Filename: App.js"
},
{
"code": null,
"e": 30034,
"s": 30023,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react';import { BrowserRouter, Route, Switch } from 'react-router-dom';import PostForm from './PostForm';import AllPost from './AllPost'; class App extends Component { render() { return ( <div className=\"App\"> <BrowserRouter> <Switch> <Route exact path ='/' render= {props => <PostForm {...props} />}> </Route> <Route exact path='/gallery' render= {props => <AllPost {...props} />}> </Route> </Switch> </BrowserRouter> </div> ); } }export default App;",
"e": 30628,
"s": 30034,
"text": null
},
{
"code": null,
"e": 30647,
"s": 30628,
"text": "Filename: Index.js"
},
{
"code": null,
"e": 30658,
"s": 30647,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App'; ReactDOM.render(<App /> , document.getElementById('root'));",
"e": 30824,
"s": 30658,
"text": null
},
{
"code": null,
"e": 30846,
"s": 30824,
"text": "Filename: PostForm.js"
},
{
"code": null,
"e": 30857,
"s": 30846,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react';import { Link } from 'react-router-dom'; const galleryStyle ={ border: 'none', margin: 0, color: '#fff', fontWeight: 'bold', padding: '16px 20px', position: 'absolute', top: '35px', right: '200px', background: '#7bc74d',}const postBtnStyle = { border: 'none', margin: 0, color: '#fff', fontWeight: 'bold', padding: '16px 20px', background: '#7D4C92 ', width: '417px',}const parentDiv = { align: 'center', margin: '0px auto auto auto', textAlign: 'center',}const formStyle = { width: '400px', border: '1px solid lightgray', margin: '10px auto 10px auto', textAlign: 'center', padding: '30px 40px 30px 40px',}const inputFields = { width: 'inherit', fontFamily: 'arial', padding: '6px',} class PostForm extends Component { handleSubmit = (e) => { e.preventDefault(); const title = this.getTitle.value; const message = this.getMessage.value; const image = this.getImage.value; localStorage.setItem('title', title); localStorage.setItem('message', message); localStorage.setItem('image', image); this.getTitle.value=''; this.getMessage.value = ''; this.getImage.value = ''; }render() { return ( <div style={parentDiv}> <h1 style={{color:'#8A2482'}}>Pics <span style={{color:'#248A6E'}}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h3>Create a new Post</h3> <form onSubmit={this.handleSubmit} style={formStyle}> <input style={inputFields} required type=\"text\" placeholder=\"Enter Post Title\" ref={(input)=> this.getTitle = input } /><br /><br /> <input style={inputFields} required type=\"text\" placeholder=\"Paste your image url here\" ref={(input) => this.getImage = input} /><br></br> <br></br> <textarea style={inputFields} required rows=\"5\" cols=\"28\" placeholder=\"Enter Comment\" ref={(input)=>this.getMessage = input}/> <br /><br /> <button style={postBtnStyle}>Post</button> </form> <Link to='/gallery'> <button style={galleryStyle}> View Gallery </button> </Link> </div> );}}export default PostForm;",
"e": 33098,
"s": 30857,
"text": null
},
{
"code": null,
"e": 33119,
"s": 33098,
"text": "Filename: AllPost.js"
},
{
"code": null,
"e": 33130,
"s": 33119,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react';import Post from './Post'; const parentDiv = { align: 'center', margin: '0px auto auto auto', textAlign: 'center',} class AllPost extends Component { render() { return ( <div style={parentDiv}> <h1 style={{color:'#8A2482'}}>Pics <span style={{color: '#248A6E'}}>Villa</span> </h1> <p>One place stop for all kinds of images</p> <hr></hr> <h1>All Posts</h1> <Post/> </div> ); }} export default AllPost;",
"e": 33632,
"s": 33130,
"text": null
},
{
"code": null,
"e": 33650,
"s": 33632,
"text": "Filename: Post.js"
},
{
"code": null,
"e": 33661,
"s": 33650,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; class Post extends Component { render() { return ( <div style={{ width: '50%', margin: '0px auto' }} > <h2>{localStorage.getItem('title')}</h2> <img src={localStorage.getItem('image')} alt={'C - language'} /> <p style={{width: '50%', margin: '0px auto'}} >{localStorage.getItem('message')}</p> </div> ); }}export default Post;",
"e": 34081,
"s": 33661,
"text": null
},
{
"code": null,
"e": 34130,
"s": 34081,
"text": "Run the application using the following command:"
},
{
"code": null,
"e": 34140,
"s": 34130,
"text": "npm start"
},
{
"code": null,
"e": 34219,
"s": 34140,
"text": "After the server is started, you will see the following output on your screen:"
},
{
"code": null,
"e": 34311,
"s": 34219,
"text": "Enter some data into the form and click on View Gallery to see the uploaded image as below:"
},
{
"code": null,
"e": 34318,
"s": 34311,
"text": "Picked"
},
{
"code": null,
"e": 34327,
"s": 34318,
"text": "react-js"
},
{
"code": null,
"e": 34351,
"s": 34327,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34362,
"s": 34351,
"text": "JavaScript"
},
{
"code": null,
"e": 34381,
"s": 34362,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34398,
"s": 34381,
"text": "Web Technologies"
},
{
"code": null,
"e": 34425,
"s": 34398,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34523,
"s": 34425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34563,
"s": 34523,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34624,
"s": 34563,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34665,
"s": 34624,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 34687,
"s": 34665,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 34741,
"s": 34687,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 34781,
"s": 34741,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34814,
"s": 34781,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34857,
"s": 34814,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34907,
"s": 34857,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to Prevent the Addition of Duplicate Elements to the Java ArrayList? - GeeksforGeeks | 11 Dec, 2020
Ever wondered how you can make an ArrayList unique? Well, in this article we’ll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are neglected can be done using various approaches discussed as below.
Example:
Input : [1, 1, 2, 2, 3, 3, 4, 5, 8]
Output: [1, 2, 3, 4, 5, 8]
Input : [1, 1, 1, 1, 1, 1, 1, 1, 1]
Output: [1]
Approach 1: contains() method
Add elements one by one.Check for their presence using the contains method.Ignore the current element if it returns true.Else add the element.
Add elements one by one.
Check for their presence using the contains method.
Ignore the current element if it returns true.
Else add the element.
Below is the implementation of the above approach:
Java
// Java Program to prevent the addition// of duplicate elements to an ArrayList. // Importing the ArrayList classimport java.util.ArrayList; class GFG { public static void main(String[] args) { // Input int array[] = { 1, 1, 2, 2, 3, 3, 4, 5, 8 }; // Creating an empty ArrayList ArrayList<Integer> ans = new ArrayList<>(); for (int i : array) { // Checking if the element is already present or // not if (!ans.contains(i)) { // Adding the element to the ArrayList if it // is not present ans.add(i); } } // Printing the elements of the ArrayList for (int i : ans) { System.out.print(i + " "); } }}
1 2 3 4 5 8
Time Complexity: O(N2), as contains method can traverse through the entire array in the worst case.
Space Complexity: O(1), as no extra space is used.
Approach 2: HashSet
Add elements one by one.Check for their presence using HashSet.Ignore the current element if it returns true.Else add the element.
Add elements one by one.
Check for their presence using HashSet.
Ignore the current element if it returns true.
Else add the element.
Below is the implementation of the above approach:
Java
// Java Program to prevent the addition// of duplicate elements to an ArrayList. // Importing the ArrayList classimport java.util.ArrayList; // Importing the HashSet classimport java.util.HashSet; class GFG { public static void main(String[] args) { // Input int array[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; // Creating an empty ArrayList ArrayList<Integer> ans = new ArrayList<>(); // Creating an empty HashSet HashSet<Integer> set = new HashSet<>(); for (int i : array) { // Checking if the element is already present or // not if (!set.contains(i)) { // Adding the element to the ArrayList if it // is not present ans.add(i); // Adding the element to the HashSet if it // is not present set.add(i); } } // Printing the elements of the ArrayList for (int i : ans) { System.out.print(i + " "); } }}
1
Time Complexity: O(n)
Space Complexity: O(n), as a HashSet is used to store the traversed elements.
Java-ArrayList
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 25603,
"s": 25237,
"text": "Ever wondered how you can make an ArrayList unique? Well, in this article we’ll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are neglected can be done using various approaches discussed as below."
},
{
"code": null,
"e": 25612,
"s": 25603,
"text": "Example:"
},
{
"code": null,
"e": 25724,
"s": 25612,
"text": "Input : [1, 1, 2, 2, 3, 3, 4, 5, 8]\nOutput: [1, 2, 3, 4, 5, 8]\n\nInput : [1, 1, 1, 1, 1, 1, 1, 1, 1]\nOutput: [1]"
},
{
"code": null,
"e": 25754,
"s": 25724,
"text": "Approach 1: contains() method"
},
{
"code": null,
"e": 25897,
"s": 25754,
"text": "Add elements one by one.Check for their presence using the contains method.Ignore the current element if it returns true.Else add the element."
},
{
"code": null,
"e": 25922,
"s": 25897,
"text": "Add elements one by one."
},
{
"code": null,
"e": 25974,
"s": 25922,
"text": "Check for their presence using the contains method."
},
{
"code": null,
"e": 26021,
"s": 25974,
"text": "Ignore the current element if it returns true."
},
{
"code": null,
"e": 26043,
"s": 26021,
"text": "Else add the element."
},
{
"code": null,
"e": 26094,
"s": 26043,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26099,
"s": 26094,
"text": "Java"
},
{
"code": "// Java Program to prevent the addition// of duplicate elements to an ArrayList. // Importing the ArrayList classimport java.util.ArrayList; class GFG { public static void main(String[] args) { // Input int array[] = { 1, 1, 2, 2, 3, 3, 4, 5, 8 }; // Creating an empty ArrayList ArrayList<Integer> ans = new ArrayList<>(); for (int i : array) { // Checking if the element is already present or // not if (!ans.contains(i)) { // Adding the element to the ArrayList if it // is not present ans.add(i); } } // Printing the elements of the ArrayList for (int i : ans) { System.out.print(i + \" \"); } }}",
"e": 26881,
"s": 26099,
"text": null
},
{
"code": null,
"e": 26893,
"s": 26881,
"text": "1 2 3 4 5 8"
},
{
"code": null,
"e": 26993,
"s": 26893,
"text": "Time Complexity: O(N2), as contains method can traverse through the entire array in the worst case."
},
{
"code": null,
"e": 27044,
"s": 26993,
"text": "Space Complexity: O(1), as no extra space is used."
},
{
"code": null,
"e": 27066,
"s": 27046,
"text": "Approach 2: HashSet"
},
{
"code": null,
"e": 27197,
"s": 27066,
"text": "Add elements one by one.Check for their presence using HashSet.Ignore the current element if it returns true.Else add the element."
},
{
"code": null,
"e": 27222,
"s": 27197,
"text": "Add elements one by one."
},
{
"code": null,
"e": 27262,
"s": 27222,
"text": "Check for their presence using HashSet."
},
{
"code": null,
"e": 27309,
"s": 27262,
"text": "Ignore the current element if it returns true."
},
{
"code": null,
"e": 27331,
"s": 27309,
"text": "Else add the element."
},
{
"code": null,
"e": 27383,
"s": 27331,
"text": " Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27388,
"s": 27383,
"text": "Java"
},
{
"code": "// Java Program to prevent the addition// of duplicate elements to an ArrayList. // Importing the ArrayList classimport java.util.ArrayList; // Importing the HashSet classimport java.util.HashSet; class GFG { public static void main(String[] args) { // Input int array[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; // Creating an empty ArrayList ArrayList<Integer> ans = new ArrayList<>(); // Creating an empty HashSet HashSet<Integer> set = new HashSet<>(); for (int i : array) { // Checking if the element is already present or // not if (!set.contains(i)) { // Adding the element to the ArrayList if it // is not present ans.add(i); // Adding the element to the HashSet if it // is not present set.add(i); } } // Printing the elements of the ArrayList for (int i : ans) { System.out.print(i + \" \"); } }}",
"e": 28427,
"s": 27388,
"text": null
},
{
"code": null,
"e": 28429,
"s": 28427,
"text": "1"
},
{
"code": null,
"e": 28451,
"s": 28429,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 28529,
"s": 28451,
"text": "Space Complexity: O(n), as a HashSet is used to store the traversed elements."
},
{
"code": null,
"e": 28544,
"s": 28529,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 28551,
"s": 28544,
"text": "Picked"
},
{
"code": null,
"e": 28556,
"s": 28551,
"text": "Java"
},
{
"code": null,
"e": 28570,
"s": 28556,
"text": "Java Programs"
},
{
"code": null,
"e": 28575,
"s": 28570,
"text": "Java"
},
{
"code": null,
"e": 28673,
"s": 28575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28688,
"s": 28673,
"text": "Stream In Java"
},
{
"code": null,
"e": 28709,
"s": 28688,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28728,
"s": 28709,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28758,
"s": 28728,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28804,
"s": 28758,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28830,
"s": 28804,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28864,
"s": 28830,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28911,
"s": 28864,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28943,
"s": 28911,
"text": "How to Iterate HashMap in Java?"
}
]
|
Error Classes in Node.js - GeeksforGeeks | 21 Aug, 2020
Node.js inherits the JavaScript and system errors from the JavaScript <Error> class and it guarantees to provide the properties which are available on that class. The JavaScript exceptions that immediately throws errors using the throw mechanism that are handled by try...catch construct that is provided by the JavaScript.
Node.js handles errors that occur during the application running, supports multiple error mechanisms i.e. how all these errors are reported and handled depends on Error type and API style. Application code can trigger user-specified errors also. All those errors that are generated by the Node.js are either the instances or inherited from the Error class. In Node.js, it experiences many types of errors while running applications that are given below:
Class: AssertionError: AssertionErrors are Extended by the <errors.Error> Class. When it detects that an exceptional logic violation has occurred that should never occur, then these errors are triggered and the assert module raises all these errors. All those errors that are thrown by the assert module are instances of AssertionError class.
Example 1: Filename: index.js
// Node.js program to demonstrate // Assertion error in JavaScript // Importing Assert moduleconst assert = require('assert'); console.log("Throws Assertion Error..."); // Comparing equality using assertassert.strictEqual( {'Alfa':'hi', 'beta':'hello'}, {'Alfa':'hi', 'beta':'hello'});// Throws AssertionError
Run index.js file using the following command:
node index.js
Output:
Throws Assertion Error>> Throws Assertion Error...>> assert.js:101 throw new AssertionError(obj);AssertionError [ERR_ASSERTION]: Values have same structure but are not reference-equal:{ Alfa: ‘hi’, beta: ‘hello’} at Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:12:8)....... operator: ?[32m’strictEqual’?[39m}
Class: RangeError: It shows that the provided argument was not within the acceptable range of values. It could be a numeric range, or outside the set of options.
Example 2: Filename: index.js
// Node.js program to demonstrate // range error in JavaScript // Importing http moduleconst http = require('http'); // Creating server with port no// out of rangevar server = http.createServer() .listen(46456656, (err, res)=>{ // Throws Range Error});
Output:
Throws Range Error>> internal/validators.js:192 throw new ERR_SOCKET_BAD_PORT(name, port);RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received 46456656....... code: ?[32m’ERR_SOCKET_BAD_PORT’?[39m}
Class: ReferenceError: It specifies that the variable anyone is trying to access is not defined. Such types of errors specify typos in code or a broken program. The instances of ReferenceError specify a bug in the code until an application is dynamically running code.
Example 3: Filename: index.js
// Node.js program to demonstrate // Reference error in JavaScript try { const alfa = 10; const beta = alfa + gamma; // Throws with a ReferenceError // because gamma is undefined} catch (err) { console.log(err.message); console.log(err); // Handle the error here.}
Output:
Throws Reference Error>> gamma is not defined>> ReferenceError: gamma is not definedat Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:128:23)......at internal/main/run_main_module.js:17:47
Class: SyntaxError: It specifies that the program is not a valid JavaScript and it may be generated as a result of code evaluation. These errors mostly happen as a result of eval, Function, require, or vm.
Example 4: Filename: index.js
// Node.js program to demonstrate // Syntax error in JavaScript try { // Import vm module require('vm').runInThisContext('alfa @ beta');} catch (error) { // Prints a Syntax Error. console.log(error);}
Output:
Throws Syntax Error>> alfa @ beta>> SyntaxError: Invalid or unexpected token at new Script (vm.js:99:7)......at internal/main/run_main_module.js:17:47
Class: SystemError: System errors that are generated by Node.js occur due to exceptions within its runtime environment. when an application violates an operating system constraint then these errors could be expected.
Example 5: Filename: index.js
// Node.js program to demonstrate // Reference error in JavaScript // Importing fs moduleconst fs = require('fs'); // Callback functionfunction errorCallback(err, data) { if (err) { console.error('There was an error', err); return; } return(data);} // Trying to read file that does not existfs.readFile('/some/non-existing/file', errorCallback);
Output:
Throws Error>> There was an error [Error: ENOENT: no such file or directory, open ‘C:\some\non-existing\file’] { errno: -4058, code: ‘ENOENT’, syscall: ‘open’, path: ‘C:\\some\\non-existing\\file’}
Class: TypeError: It specifies that the argument provided is not an allowable type. For example, calling a function that actually doesn’t exist would be a TypeError. As if the form is of argument validation, it throws TypeError instances immediately.
Example 6: Filename: index.js
// Node.js program to demonstrate // Type error in JavaScript try { if(1) { if(2) { console.loo('alfa') } }} catch (error) {console.log(error); }
Run index.js file using the following command:
node index.js
Output:
Throws Type Error>> TypeError: console.loo is not a function at Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:104:15)......at internal/main/run_main_module.js:17:47
Reference: https://nodejs.org/api/errors.html#errors_class_assertionerror
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26109,
"s": 26081,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 26433,
"s": 26109,
"text": "Node.js inherits the JavaScript and system errors from the JavaScript <Error> class and it guarantees to provide the properties which are available on that class. The JavaScript exceptions that immediately throws errors using the throw mechanism that are handled by try...catch construct that is provided by the JavaScript."
},
{
"code": null,
"e": 26887,
"s": 26433,
"text": "Node.js handles errors that occur during the application running, supports multiple error mechanisms i.e. how all these errors are reported and handled depends on Error type and API style. Application code can trigger user-specified errors also. All those errors that are generated by the Node.js are either the instances or inherited from the Error class. In Node.js, it experiences many types of errors while running applications that are given below:"
},
{
"code": null,
"e": 27230,
"s": 26887,
"text": "Class: AssertionError: AssertionErrors are Extended by the <errors.Error> Class. When it detects that an exceptional logic violation has occurred that should never occur, then these errors are triggered and the assert module raises all these errors. All those errors that are thrown by the assert module are instances of AssertionError class."
},
{
"code": null,
"e": 27260,
"s": 27230,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // Assertion error in JavaScript // Importing Assert moduleconst assert = require('assert'); console.log(\"Throws Assertion Error...\"); // Comparing equality using assertassert.strictEqual( {'Alfa':'hi', 'beta':'hello'}, {'Alfa':'hi', 'beta':'hello'});// Throws AssertionError",
"e": 27580,
"s": 27260,
"text": null
},
{
"code": null,
"e": 27627,
"s": 27580,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 27641,
"s": 27627,
"text": "node index.js"
},
{
"code": null,
"e": 27649,
"s": 27641,
"text": "Output:"
},
{
"code": null,
"e": 27971,
"s": 27649,
"text": "Throws Assertion Error>> Throws Assertion Error...>> assert.js:101 throw new AssertionError(obj);AssertionError [ERR_ASSERTION]: Values have same structure but are not reference-equal:{ Alfa: ‘hi’, beta: ‘hello’} at Object.<anonymous> (C:\\Users\\Ajay Kumar\\Desktop\\test2.js:12:8)....... operator: ?[32m’strictEqual’?[39m}"
},
{
"code": null,
"e": 28133,
"s": 27971,
"text": "Class: RangeError: It shows that the provided argument was not within the acceptable range of values. It could be a numeric range, or outside the set of options."
},
{
"code": null,
"e": 28163,
"s": 28133,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // range error in JavaScript // Importing http moduleconst http = require('http'); // Creating server with port no// out of rangevar server = http.createServer() .listen(46456656, (err, res)=>{ // Throws Range Error});",
"e": 28424,
"s": 28163,
"text": null
},
{
"code": null,
"e": 28432,
"s": 28424,
"text": "Output:"
},
{
"code": null,
"e": 28663,
"s": 28432,
"text": "Throws Range Error>> internal/validators.js:192 throw new ERR_SOCKET_BAD_PORT(name, port);RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received 46456656....... code: ?[32m’ERR_SOCKET_BAD_PORT’?[39m}"
},
{
"code": null,
"e": 28932,
"s": 28663,
"text": "Class: ReferenceError: It specifies that the variable anyone is trying to access is not defined. Such types of errors specify typos in code or a broken program. The instances of ReferenceError specify a bug in the code until an application is dynamically running code."
},
{
"code": null,
"e": 28962,
"s": 28932,
"text": "Example 3: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // Reference error in JavaScript try { const alfa = 10; const beta = alfa + gamma; // Throws with a ReferenceError // because gamma is undefined} catch (err) { console.log(err.message); console.log(err); // Handle the error here.}",
"e": 29240,
"s": 28962,
"text": null
},
{
"code": null,
"e": 29248,
"s": 29240,
"text": "Output:"
},
{
"code": null,
"e": 29447,
"s": 29248,
"text": "Throws Reference Error>> gamma is not defined>> ReferenceError: gamma is not definedat Object.<anonymous> (C:\\Users\\Ajay Kumar\\Desktop\\test2.js:128:23)......at internal/main/run_main_module.js:17:47"
},
{
"code": null,
"e": 29653,
"s": 29447,
"text": "Class: SyntaxError: It specifies that the program is not a valid JavaScript and it may be generated as a result of code evaluation. These errors mostly happen as a result of eval, Function, require, or vm."
},
{
"code": null,
"e": 29683,
"s": 29653,
"text": "Example 4: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // Syntax error in JavaScript try { // Import vm module require('vm').runInThisContext('alfa @ beta');} catch (error) { // Prints a Syntax Error. console.log(error);}",
"e": 29893,
"s": 29683,
"text": null
},
{
"code": null,
"e": 29901,
"s": 29893,
"text": "Output:"
},
{
"code": null,
"e": 30054,
"s": 29901,
"text": "Throws Syntax Error>> alfa @ beta>> SyntaxError: Invalid or unexpected token at new Script (vm.js:99:7)......at internal/main/run_main_module.js:17:47"
},
{
"code": null,
"e": 30271,
"s": 30054,
"text": "Class: SystemError: System errors that are generated by Node.js occur due to exceptions within its runtime environment. when an application violates an operating system constraint then these errors could be expected."
},
{
"code": null,
"e": 30301,
"s": 30271,
"text": "Example 5: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // Reference error in JavaScript // Importing fs moduleconst fs = require('fs'); // Callback functionfunction errorCallback(err, data) { if (err) { console.error('There was an error', err); return; } return(data);} // Trying to read file that does not existfs.readFile('/some/non-existing/file', errorCallback);",
"e": 30659,
"s": 30301,
"text": null
},
{
"code": null,
"e": 30667,
"s": 30659,
"text": "Output:"
},
{
"code": null,
"e": 30865,
"s": 30667,
"text": "Throws Error>> There was an error [Error: ENOENT: no such file or directory, open ‘C:\\some\\non-existing\\file’] { errno: -4058, code: ‘ENOENT’, syscall: ‘open’, path: ‘C:\\\\some\\\\non-existing\\\\file’}"
},
{
"code": null,
"e": 31116,
"s": 30865,
"text": "Class: TypeError: It specifies that the argument provided is not an allowable type. For example, calling a function that actually doesn’t exist would be a TypeError. As if the form is of argument validation, it throws TypeError instances immediately."
},
{
"code": null,
"e": 31146,
"s": 31116,
"text": "Example 6: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate // Type error in JavaScript try { if(1) { if(2) { console.loo('alfa') } }} catch (error) {console.log(error); }",
"e": 31307,
"s": 31146,
"text": null
},
{
"code": null,
"e": 31354,
"s": 31307,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 31368,
"s": 31354,
"text": "node index.js"
},
{
"code": null,
"e": 31376,
"s": 31368,
"text": "Output:"
},
{
"code": null,
"e": 31554,
"s": 31376,
"text": "Throws Type Error>> TypeError: console.loo is not a function at Object.<anonymous> (C:\\Users\\Ajay Kumar\\Desktop\\test2.js:104:15)......at internal/main/run_main_module.js:17:47"
},
{
"code": null,
"e": 31628,
"s": 31554,
"text": "Reference: https://nodejs.org/api/errors.html#errors_class_assertionerror"
},
{
"code": null,
"e": 31641,
"s": 31628,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 31649,
"s": 31641,
"text": "Node.js"
},
{
"code": null,
"e": 31666,
"s": 31649,
"text": "Web Technologies"
},
{
"code": null,
"e": 31764,
"s": 31666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31794,
"s": 31764,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 31851,
"s": 31794,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 31905,
"s": 31851,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 31942,
"s": 31905,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 31982,
"s": 31942,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 32022,
"s": 31982,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32067,
"s": 32022,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32110,
"s": 32067,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32172,
"s": 32110,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
MathF.Floor() Method in C# with Examples - GeeksforGeeks | 04 Apr, 2019
In C#, MathF.Floor(Single) is a MathF class method. This method is used to find the largest integer , which is less than or equal to the specified float value in the argument list.
Syntax: public static float Floor (float x);Here, x is the float(Single) value whose floor value has to be calculated.
Return Type: This method return the largest integral value which will be less than or equal to x.
Example:
// C# program to illustrate the// MathF.Floor(Single) Methodusing System; class GFG { // Main method static void Main() { // taking float values float x1 = 37.00f; float x2 = 99.99f; float x3 = 0.2154f; float x4 = 123.123f; float x5 = -2.2f; float x6 = -123.123f; // calling the method result(x1); result(x2); result(x3); result(x4); result(x5); result(x6); } public static void result(float t1) { // Print the original values // and Floor values Console.WriteLine("Input Value = " + t1); // using the MathF.Floor() Method Console.WriteLine("Floor value = " + MathF.Floor(t1)); }}
Input Value = 37
Floor value = 37
Input Value = 99.99
Floor value = 99
Input Value = 0.2154
Floor value = 0
Input Value = 123.123
Floor value = 123
Input Value = -2.2
Floor value = -3
Input Value = -123.123
Floor value = -124
CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 24483,
"s": 24302,
"text": "In C#, MathF.Floor(Single) is a MathF class method. This method is used to find the largest integer , which is less than or equal to the specified float value in the argument list."
},
{
"code": null,
"e": 24602,
"s": 24483,
"text": "Syntax: public static float Floor (float x);Here, x is the float(Single) value whose floor value has to be calculated."
},
{
"code": null,
"e": 24700,
"s": 24602,
"text": "Return Type: This method return the largest integral value which will be less than or equal to x."
},
{
"code": null,
"e": 24709,
"s": 24700,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// MathF.Floor(Single) Methodusing System; class GFG { // Main method static void Main() { // taking float values float x1 = 37.00f; float x2 = 99.99f; float x3 = 0.2154f; float x4 = 123.123f; float x5 = -2.2f; float x6 = -123.123f; // calling the method result(x1); result(x2); result(x3); result(x4); result(x5); result(x6); } public static void result(float t1) { // Print the original values // and Floor values Console.WriteLine(\"Input Value = \" + t1); // using the MathF.Floor() Method Console.WriteLine(\"Floor value = \" + MathF.Floor(t1)); }}",
"e": 25482,
"s": 24709,
"text": null
},
{
"code": null,
"e": 25709,
"s": 25482,
"text": "Input Value = 37\nFloor value = 37\nInput Value = 99.99\nFloor value = 99\nInput Value = 0.2154\nFloor value = 0\nInput Value = 123.123\nFloor value = 123\nInput Value = -2.2\nFloor value = -3\nInput Value = -123.123\nFloor value = -124\n"
},
{
"code": null,
"e": 25728,
"s": 25709,
"text": "CSharp-MathF-Class"
},
{
"code": null,
"e": 25742,
"s": 25728,
"text": "CSharp-method"
},
{
"code": null,
"e": 25745,
"s": 25742,
"text": "C#"
},
{
"code": null,
"e": 25843,
"s": 25745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25861,
"s": 25843,
"text": "Destructors in C#"
},
{
"code": null,
"e": 25884,
"s": 25861,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25912,
"s": 25884,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25952,
"s": 25912,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25995,
"s": 25952,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26017,
"s": 25995,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26034,
"s": 26017,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26050,
"s": 26034,
"text": "C# | List Class"
},
{
"code": null,
"e": 26100,
"s": 26050,
"text": "Difference between Hashtable and Dictionary in C#"
}
]
|
Pointer to an Array in C | It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.
Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance −
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on. Given below is the example to show all the concepts discussed above −
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000
In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above example.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2196,
"s": 2084,
"text": "It is most likely that you would not understand this section until you are through with the chapter 'Pointers'."
},
{
"code": null,
"e": 2368,
"s": 2196,
"text": "Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −"
},
{
"code": null,
"e": 2389,
"s": 2368,
"text": "double balance[50];\n"
},
{
"code": null,
"e": 2586,
"s": 2389,
"text": "balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance −"
},
{
"code": null,
"e": 2632,
"s": 2586,
"text": "double *p;\ndouble balance[10];\n\np = balance;\n"
},
{
"code": null,
"e": 2784,
"s": 2632,
"text": "It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]."
},
{
"code": null,
"e": 2980,
"s": 2784,
"text": "Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on. Given below is the example to show all the concepts discussed above −"
},
{
"code": null,
"e": 3493,
"s": 2980,
"text": "#include <stdio.h>\n\nint main () {\n\n /* an array with 5 elements */\n double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n double *p;\n int i;\n\n p = balance;\n \n /* output each array element's value */\n printf( \"Array values using pointer\\n\");\n\t\n for ( i = 0; i < 5; i++ ) {\n printf(\"*(p + %d) : %f\\n\", i, *(p + i) );\n }\n\n printf( \"Array values using balance as address\\n\");\n\t\n for ( i = 0; i < 5; i++ ) {\n printf(\"*(balance + %d) : %f\\n\", i, *(balance + i) );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3574,
"s": 3493,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3880,
"s": 3574,
"text": "Array values using pointer\n*(p + 0) : 1000.000000\n*(p + 1) : 2.000000\n*(p + 2) : 3.400000\n*(p + 3) : 17.000000\n*(p + 4) : 50.000000\nArray values using balance as address\n*(balance + 0) : 1000.000000\n*(balance + 1) : 2.000000\n*(balance + 2) : 3.400000\n*(balance + 3) : 17.000000\n*(balance + 4) : 50.000000\n"
},
{
"code": null,
"e": 4129,
"s": 3880,
"text": "In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above example."
},
{
"code": null,
"e": 4136,
"s": 4129,
"text": " Print"
},
{
"code": null,
"e": 4147,
"s": 4136,
"text": " Add Notes"
}
]
|
How to GROUP BY in a select query on positive or negative values? | Following is the syntax to GROUP BY in a select query on positive or negative values:
select *from yourTableName group by -yourColumnName;
Let us first create a table:
mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (0.60 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(-20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(-10);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(-20);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(-30);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.12 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output
+-------+
| Value |
+-------+
| -10 |
| -20 |
| 20 |
| 10 |
| -10 |
| -10 |
| -20 |
| -30 |
| 30 |
+-------+
9 rows in set (0.00 sec)
Following is the query to group by positive and negative values:
mysql> select *from DemoTable group by -Value;
This will produce the following output
+-------+
| Value |
+-------+
| -10 |
| -20 |
| 20 |
| 10 |
| -30 |
| 30 |
+-------+
6 rows in set (0.00 sec) | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Following is the syntax to GROUP BY in a select query on positive or negative values:"
},
{
"code": null,
"e": 1201,
"s": 1148,
"text": "select *from yourTableName group by -yourColumnName;"
},
{
"code": null,
"e": 1230,
"s": 1201,
"text": "Let us first create a table:"
},
{
"code": null,
"e": 1310,
"s": 1230,
"text": "mysql> create table DemoTable (Value int);\nQuery OK, 0 rows affected (0.60 sec)"
},
{
"code": null,
"e": 1391,
"s": 1310,
"text": "Following is the query to insert some records in the table using insert command:"
},
{
"code": null,
"e": 2090,
"s": 1391,
"text": "mysql> insert into DemoTable values(-10);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable values(-20);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(-10);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(-10);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(-20);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(-30);\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2169,
"s": 2090,
"text": "Following is the query to display records from the table using select command:"
},
{
"code": null,
"e": 2200,
"s": 2169,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2239,
"s": 2200,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2394,
"s": 2239,
"text": "+-------+\n| Value |\n+-------+\n| -10 |\n| -20 |\n| 20 |\n| 10 |\n| -10 |\n| -10 |\n| -20 |\n| -30 |\n| 30 |\n+-------+\n9 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2459,
"s": 2394,
"text": "Following is the query to group by positive and negative values:"
},
{
"code": null,
"e": 2506,
"s": 2459,
"text": "mysql> select *from DemoTable group by -Value;"
},
{
"code": null,
"e": 2545,
"s": 2506,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2670,
"s": 2545,
"text": "+-------+\n| Value |\n+-------+\n| -10 |\n| -20 |\n| 20 |\n| 10 |\n| -30 |\n| 30 |\n+-------+\n6 rows in set (0.00 sec)"
}
]
|
Tryit Editor v3.7 | Tryit: HTML image - size attributes or style? | []
|
HTML DOM childElementCount Property | The HTML DOM childElementCount property is a read-only property that returns the number of child elements of a given element. The return type of the childElementCount is of unsigned long. It will only return the child element of the node on which it is queried and not all the child nodes of a HTML document.
Following is the syntax for childElementCount property −
node.childElementCount
Let us see an example for the HTML DOM childElementCount property −
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid blue;
margin: 7px;
padding-left:20px;
}
</style>
</head>
<body>
<p>Click the button below to find out the no of children of the div element</p>
<button onclick="childCount()">COUNT</button>
<div id="myDIV">
<h3>HEADING</h3>
<p>First p element</p>
<p>Second p element</p>
</div>
<p id="Sample"></p>
<script>
function childCount() {
var x = document.getElementById("myDIV").childElementCount;
document.getElementById("Sample").innerHTML = "The div element has "+x+" children";
}
</script>
</body>
</html>
This will produce the following output −
On clicking the COUNT button −
In the above example −
We have created a <div> element with id “myDIV” and three elements inside it. Two <p> elements and a <h3> header. We have also added colored border, margin and padding to the div to distinguish it from other elements −
div {
border: 2px solid blue;
margin: 7px;
padding-left:20px;
}
<div id="myDIV">
<h3>HEADING</h3>
<p>First p element</p>
<p>Second p element</p>
</div>
We have then created a button COUNT which will execute the childCount() method on click.
<button onclick="childCount()">COUNT</button>
The childCount() method takes the element with id “myDIV”, which in our case is the <div>, element and assigns its childElementCount property value to variable x. Since we have two<p> elements and a <h3> element inside the <div>, so the childElementCount returned 3.
The value returned is then displayed in the paragraph with id “Sample” using the innerHTML() method on the paragraph −
function childCount() {
var x = document.getElementById("myDIV").childElementCount;
document.getElementById("Sample").innerHTML = "The div element has "+x+" children";
} | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "The HTML DOM childElementCount property is a read-only property that returns the number of child elements of a given element. The return type of the childElementCount is of unsigned long. It will only return the child element of the node on which it is queried and not all the child nodes of a HTML document."
},
{
"code": null,
"e": 1428,
"s": 1371,
"text": "Following is the syntax for childElementCount property −"
},
{
"code": null,
"e": 1451,
"s": 1428,
"text": "node.childElementCount"
},
{
"code": null,
"e": 1519,
"s": 1451,
"text": "Let us see an example for the HTML DOM childElementCount property −"
},
{
"code": null,
"e": 2126,
"s": 1519,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n div {\n border: 2px solid blue;\n margin: 7px;\n padding-left:20px;\n }\n</style>\n</head>\n<body>\n<p>Click the button below to find out the no of children of the div element</p>\n<button onclick=\"childCount()\">COUNT</button>\n<div id=\"myDIV\">\n<h3>HEADING</h3>\n<p>First p element</p>\n<p>Second p element</p>\n</div>\n<p id=\"Sample\"></p>\n<script>\n function childCount() {\n var x = document.getElementById(\"myDIV\").childElementCount;\n document.getElementById(\"Sample\").innerHTML = \"The div element has \"+x+\" children\";\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2167,
"s": 2126,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2198,
"s": 2167,
"text": "On clicking the COUNT button −"
},
{
"code": null,
"e": 2221,
"s": 2198,
"text": "In the above example −"
},
{
"code": null,
"e": 2440,
"s": 2221,
"text": "We have created a <div> element with id “myDIV” and three elements inside it. Two <p> elements and a <h3> header. We have also added colored border, margin and padding to the div to distinguish it from other elements −"
},
{
"code": null,
"e": 2601,
"s": 2440,
"text": "div {\n border: 2px solid blue;\n margin: 7px;\n padding-left:20px;\n}\n<div id=\"myDIV\">\n<h3>HEADING</h3>\n<p>First p element</p>\n<p>Second p element</p>\n</div>"
},
{
"code": null,
"e": 2690,
"s": 2601,
"text": "We have then created a button COUNT which will execute the childCount() method on click."
},
{
"code": null,
"e": 2736,
"s": 2690,
"text": "<button onclick=\"childCount()\">COUNT</button>"
},
{
"code": null,
"e": 3003,
"s": 2736,
"text": "The childCount() method takes the element with id “myDIV”, which in our case is the <div>, element and assigns its childElementCount property value to variable x. Since we have two<p> elements and a <h3> element inside the <div>, so the childElementCount returned 3."
},
{
"code": null,
"e": 3122,
"s": 3003,
"text": "The value returned is then displayed in the paragraph with id “Sample” using the innerHTML() method on the paragraph −"
},
{
"code": null,
"e": 3298,
"s": 3122,
"text": "function childCount() {\n var x = document.getElementById(\"myDIV\").childElementCount;\n document.getElementById(\"Sample\").innerHTML = \"The div element has \"+x+\" children\";\n}"
}
]
|
Image Classification Using Pre-Trained Model | In this lesson, you will learn to use a pre-trained model to detect objects in a given image. You will use squeezenet pre-trained module that detects and classifies the objects in a given image with a great accuracy.
Open a new Juypter notebook and follow the steps to develop this image classification application.
First, we import the required packages using the below code −
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace, models
import numpy as np
import skimage.io
import skimage.transform
from matplotlib import pyplot
import os
import urllib.request as urllib2
import operator
Next, we set up a few variables −
INPUT_IMAGE_SIZE = 227
mean = 128
The images used for training will obviously be of varied sizes. All these images must be converted into a fixed size for accurate training. Likewise, the test images and the image which you want to predict in the production environment must also be converted to the size, the same as the one used during training. Thus, we create a variable above called INPUT_IMAGE_SIZE having value 227. Hence, we will convert all our images to the size 227x227 before using it in our classifier.
We also declare a variable called mean having value 128, which is used later for improving the classification results.
Next, we will develop two functions for processing the image.
The image processing consists of two steps. First one is to resize the image, and the second one is to centrally crop the image. For these two steps, we will write two functions for resizing and cropping.
First, we will write a function for resizing the image. As said earlier, we will resize the image to 227x227. So let us define the function resize as follows −
def resize(img, input_height, input_width):
We obtain the aspect ratio of the image by dividing the width by the height.
original_aspect = img.shape[1]/float(img.shape[0])
If the aspect ratio is greater than 1, it indicates that the image is wide, that to say it is in the landscape mode. We now adjust the image height and return the resized image using the following code −
if(original_aspect>1):
new_height = int(original_aspect * input_height)
return skimage.transform.resize(img, (input_width,
new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
If the aspect ratio is less than 1, it indicates the portrait mode. We now adjust the width using the following code −
if(original_aspect<1):
new_width = int(input_width/original_aspect)
return skimage.transform.resize(img, (new_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
If the aspect ratio equals 1, we do not make any height/width adjustments.
if(original_aspect == 1):
return skimage.transform.resize(img, (input_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
The full function code is given below for your quick reference −
def resize(img, input_height, input_width):
original_aspect = img.shape[1]/float(img.shape[0])
if(original_aspect>1):
new_height = int(original_aspect * input_height)
return skimage.transform.resize(img, (input_width,
new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
if(original_aspect<1):
new_width = int(input_width/original_aspect)
return skimage.transform.resize(img, (new_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
if(original_aspect == 1):
return skimage.transform.resize(img, (input_width,
input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)
We will now write a function for cropping the image around its center.
We declare the crop_image function as follows −
def crop_image(img,cropx,cropy):
We extract the dimensions of the image using the following statement −
y,x,c = img.shape
We create a new starting point for the image using the following two lines of code −
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
Finally, we return the cropped image by creating an image object with the new dimensions −
return img[starty:starty+cropy,startx:startx+cropx]
The entire function code is given below for your quick reference −
def crop_image(img,cropx,cropy):
y,x,c = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
Now, we will write code to test these functions.
Firstly, copy an image file into images subfolder within your project directory. tree.jpg file is copied in the project. The following Python code loads the image and displays it on the console −
img = skimage.img_as_float(skimage.io.imread("images/tree.jpg")).astype(np.float32)
print("Original Image Shape: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Original image')
The output is as follows −
Note that size of the original image is 600 x 960. We need to resize this to our specification of 227 x 227. Calling our earlier-defined resizefunction does this job.
img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after resizing: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Resized image')
The output is as given below −
Note that now the image size is 227 x 363. We need to crop this to 227 x 227 for the final feed to our algorithm. We call the previously-defined crop function for this purpose.
img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after cropping: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Center Cropped')
Below mentioned is the output of the code −
At this point, the image is of size 227 x 227 and is ready for further processing. We now swap the image axes to extract the three colours into three different zones.
img = img.swapaxes(1, 2).swapaxes(0, 1)
print("CHW Image Shape: " , img.shape)
Given below is the output −
CHW Image Shape: (3, 227, 227)
Note that the last axis has now become the first dimension in the array. We will now plot the three channels using the following code −
pyplot.figure()
for i in range(3):
pyplot.subplot(1, 3, i+1)
pyplot.imshow(img[i])
pyplot.axis('off')
pyplot.title('RGB channel %d' % (i+1))
The output is stated below −
Finally, we do some additional processing on the image such as converting Red Green Blue to Blue Green Red (RGB to BGR), removing mean for better results and adding batch size axis using the following three lines of code −
# convert RGB --> BGR
img = img[(2, 1, 0), :, :]
# remove mean
img = img * 255 - mean
# add batch size axis
img = img[np.newaxis, :, :, :].astype(np.float32)
At this point, your image is in NCHW format and is ready for feeding into our network. Next, we will load our pre-trained model files and feed the above image into it for prediction.
We first setup the paths for the init and predict networks defined in the pre-trained models of Caffe.
Remember from our earlier discussion, all the pre-trained models are installed in the models folder. We set up the path to this folder as follows −
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
We set up the path to the init_net protobuf file of the squeezenet model as follows −
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
Likewise, we set up the path to the predict_net protobuf as follows −
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
We print the two paths for diagnosis purpose −
print(INIT_NET)
print(PREDICT_NET)
The above code along with the output is given here for your quick reference −
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
print(INIT_NET)
print(PREDICT_NET)
The output is mentioned below −
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb
/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb
Next, we will create a predictor.
We read the model files using the following two statements −
with open(INIT_NET, "rb") as f:
init_net = f.read()
with open(PREDICT_NET, "rb") as f:
predict_net = f.read()
The predictor is created by passing pointers to the two files as parameters to the Predictor function.
p = workspace.Predictor(init_net, predict_net)
The p object is the predictor, which is used for predicting the objects in any given image. Note that each input image must be in NCHW format as what we have done earlier to our tree.jpg file.
To predict the objects in a given image is trivial - just executing a single line of command. We call run method on the predictor object for an object detection in a given image.
results = p.run({'data': img})
The prediction results are now available in the results object, which we convert to an array for our readability.
results = np.asarray(results)
Print the dimensions of the array for your understanding using the following statement −
print("results shape: ", results.shape)
The output is as shown below −
results shape: (1, 1, 1000, 1, 1)
We will now remove the unnecessary axis −
preds = np.squeeze(results)
The topmost predication can now be retrieved by taking the max value in the preds array.
curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))
print("Prediction: ", curr_pred)
print("Confidence: ", curr_conf)
The output is as follows −
Prediction: 984
Confidence: 0.89235985
As you see the model has predicted an object with an index value 984 with 89% confidence. The index of 984 does not make much sense to us in understanding what kind of object is detected. We need to get the stringified name for the object using its index value. The kind of objects that the model recognizes along with their corresponding index values are available on a github repository.
Now, we will see how to retrieve the name for our object having index value of 984.
We create a URL object to the github repository as follows −
codes = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac0
71eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
We read the contents of the URL −
response = urllib2.urlopen(codes)
The response will contain a list of all codes and its descriptions. Few lines of the response are shown below for your understanding of what it contains −
5: 'electric ray, crampfish, numbfish, torpedo',
6: 'stingray',
7: 'cock',
8: 'hen',
9: 'ostrich, Struthio camelus',
10: 'brambling, Fringilla montifringilla',
We now iterate the entire array to locate our desired code of 984 using a for loop as follows −
for line in response:
mystring = line.decode('ascii')
code, result = mystring.partition(":")[::2]
code = code.strip()
result = result.replace("'", "")
if (code == str(curr_pred)):
name = result.split(",")[0][1:]
print("Model predicts", name, "with", curr_conf, "confidence")
When you run the code, you will see the following output −
Model predicts rapeseed with 0.89235985 confidence
You may now try the model on another image.
To predict another image, simply copy the image file into the images folder of your project directory. This is the directory in which our earlier tree.jpg file is stored. Change the name of the image file in the code. Only one change is required as shown below
img = skimage.img_as_float(skimage.io.imread("images/pretzel.jpg")).astype(np.float32)
The original picture and the prediction result are shown below −
The output is mentioned below −
Model predicts pretzel with 0.99999976 confidence
As you see the pre-trained model is able to detect objects in a given image with a great amount of accuracy.
The full source for the above code that uses a pre-trained model for object detection in a given image is mentioned here for your quick reference −
def crop_image(img,cropx,cropy):
y,x,c = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
img = skimage.img_as_float(skimage.io.imread("images/pretzel.jpg")).astype(np.float32)
print("Original Image Shape: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Original image')
img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after resizing: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Resized image')
img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)
print("Image Shape after cropping: " , img.shape)
pyplot.figure()
pyplot.imshow(img)
pyplot.title('Center Cropped')
img = img.swapaxes(1, 2).swapaxes(0, 1)
print("CHW Image Shape: " , img.shape)
pyplot.figure()
for i in range(3):
pyplot.subplot(1, 3, i+1)
pyplot.imshow(img[i])
pyplot.axis('off')
pyplot.title('RGB channel %d' % (i+1))
# convert RGB --> BGR
img = img[(2, 1, 0), :, :]
# remove mean
img = img * 255 - mean
# add batch size axis
img = img[np.newaxis, :, :, :].astype(np.float32)
CAFFE_MODELS = os.path.expanduser("/anaconda3/lib/python3.7/site-packages/caffe2/python/models")
INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')
PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')
print(INIT_NET)
print(PREDICT_NET)
with open(INIT_NET, "rb") as f:
init_net = f.read()
with open(PREDICT_NET, "rb") as f:
predict_net = f.read()
p = workspace.Predictor(init_net, predict_net)
results = p.run({'data': img})
results = np.asarray(results)
print("results shape: ", results.shape)
preds = np.squeeze(results)
curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))
print("Prediction: ", curr_pred)
print("Confidence: ", curr_conf)
codes = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
response = urllib2.urlopen(codes)
for line in response:
mystring = line.decode('ascii')
code, result = mystring.partition(":")[::2]
code = code.strip()
result = result.replace("'", "")
if (code == str(curr_pred)):
name = result.split(",")[0][1:]
print("Model predicts", name, "with", curr_conf, "confidence")
By this time, you know how to use a pre-trained model for doing the predictions on your dataset.
What’s next is to learn how to define your neural network (NN) architectures in Caffe2 and train them on your dataset. We will now learn how to create a trivial single layer NN.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2008,
"s": 1791,
"text": "In this lesson, you will learn to use a pre-trained model to detect objects in a given image. You will use squeezenet pre-trained module that detects and classifies the objects in a given image with a great accuracy."
},
{
"code": null,
"e": 2107,
"s": 2008,
"text": "Open a new Juypter notebook and follow the steps to develop this image classification application."
},
{
"code": null,
"e": 2169,
"s": 2107,
"text": "First, we import the required packages using the below code −"
},
{
"code": null,
"e": 2407,
"s": 2169,
"text": "from caffe2.proto import caffe2_pb2\nfrom caffe2.python import core, workspace, models\nimport numpy as np\nimport skimage.io\nimport skimage.transform\nfrom matplotlib import pyplot\nimport os\nimport urllib.request as urllib2\nimport operator\n"
},
{
"code": null,
"e": 2441,
"s": 2407,
"text": "Next, we set up a few variables −"
},
{
"code": null,
"e": 2476,
"s": 2441,
"text": "INPUT_IMAGE_SIZE = 227\nmean = 128\n"
},
{
"code": null,
"e": 2958,
"s": 2476,
"text": "The images used for training will obviously be of varied sizes. All these images must be converted into a fixed size for accurate training. Likewise, the test images and the image which you want to predict in the production environment must also be converted to the size, the same as the one used during training. Thus, we create a variable above called INPUT_IMAGE_SIZE having value 227. Hence, we will convert all our images to the size 227x227 before using it in our classifier."
},
{
"code": null,
"e": 3077,
"s": 2958,
"text": "We also declare a variable called mean having value 128, which is used later for improving the classification results."
},
{
"code": null,
"e": 3139,
"s": 3077,
"text": "Next, we will develop two functions for processing the image."
},
{
"code": null,
"e": 3344,
"s": 3139,
"text": "The image processing consists of two steps. First one is to resize the image, and the second one is to centrally crop the image. For these two steps, we will write two functions for resizing and cropping."
},
{
"code": null,
"e": 3504,
"s": 3344,
"text": "First, we will write a function for resizing the image. As said earlier, we will resize the image to 227x227. So let us define the function resize as follows −"
},
{
"code": null,
"e": 3549,
"s": 3504,
"text": "def resize(img, input_height, input_width):\n"
},
{
"code": null,
"e": 3626,
"s": 3549,
"text": "We obtain the aspect ratio of the image by dividing the width by the height."
},
{
"code": null,
"e": 3678,
"s": 3626,
"text": "original_aspect = img.shape[1]/float(img.shape[0])\n"
},
{
"code": null,
"e": 3882,
"s": 3678,
"text": "If the aspect ratio is greater than 1, it indicates that the image is wide, that to say it is in the landscape mode. We now adjust the image height and return the resized image using the following code −"
},
{
"code": null,
"e": 4091,
"s": 3882,
"text": "if(original_aspect>1):\n new_height = int(original_aspect * input_height)\n return skimage.transform.resize(img, (input_width,\n new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 4210,
"s": 4091,
"text": "If the aspect ratio is less than 1, it indicates the portrait mode. We now adjust the width using the following code −"
},
{
"code": null,
"e": 4415,
"s": 4210,
"text": "if(original_aspect<1):\n new_width = int(input_width/original_aspect)\n return skimage.transform.resize(img, (new_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 4490,
"s": 4415,
"text": "If the aspect ratio equals 1, we do not make any height/width adjustments."
},
{
"code": null,
"e": 4652,
"s": 4490,
"text": "if(original_aspect == 1):\n return skimage.transform.resize(img, (input_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 4717,
"s": 4652,
"text": "The full function code is given below for your quick reference −"
},
{
"code": null,
"e": 5435,
"s": 4717,
"text": "def resize(img, input_height, input_width):\n original_aspect = img.shape[1]/float(img.shape[0])\n if(original_aspect>1):\n new_height = int(original_aspect * input_height)\n return skimage.transform.resize(img, (input_width,\n\t new_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n if(original_aspect<1):\n new_width = int(input_width/original_aspect)\n return skimage.transform.resize(img, (new_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n if(original_aspect == 1):\n return skimage.transform.resize(img, (input_width,\n input_height), mode='constant', anti_aliasing=True, anti_aliasing_sigma=None)\n"
},
{
"code": null,
"e": 5506,
"s": 5435,
"text": "We will now write a function for cropping the image around its center."
},
{
"code": null,
"e": 5554,
"s": 5506,
"text": "We declare the crop_image function as follows −"
},
{
"code": null,
"e": 5588,
"s": 5554,
"text": "def crop_image(img,cropx,cropy):\n"
},
{
"code": null,
"e": 5659,
"s": 5588,
"text": "We extract the dimensions of the image using the following statement −"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "y,x,c = img.shape\n"
},
{
"code": null,
"e": 5763,
"s": 5678,
"text": "We create a new starting point for the image using the following two lines of code −"
},
{
"code": null,
"e": 5814,
"s": 5763,
"text": "startx = x//2-(cropx//2)\nstarty = y//2-(cropy//2)\n"
},
{
"code": null,
"e": 5905,
"s": 5814,
"text": "Finally, we return the cropped image by creating an image object with the new dimensions −"
},
{
"code": null,
"e": 5958,
"s": 5905,
"text": "return img[starty:starty+cropy,startx:startx+cropx]\n"
},
{
"code": null,
"e": 6025,
"s": 5958,
"text": "The entire function code is given below for your quick reference −"
},
{
"code": null,
"e": 6191,
"s": 6025,
"text": "def crop_image(img,cropx,cropy):\n y,x,c = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return img[starty:starty+cropy,startx:startx+cropx]\n"
},
{
"code": null,
"e": 6240,
"s": 6191,
"text": "Now, we will write code to test these functions."
},
{
"code": null,
"e": 6436,
"s": 6240,
"text": "Firstly, copy an image file into images subfolder within your project directory. tree.jpg file is copied in the project. The following Python code loads the image and displays it on the console −"
},
{
"code": null,
"e": 6631,
"s": 6436,
"text": "img = skimage.img_as_float(skimage.io.imread(\"images/tree.jpg\")).astype(np.float32)\nprint(\"Original Image Shape: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Original image')\n"
},
{
"code": null,
"e": 6658,
"s": 6631,
"text": "The output is as follows −"
},
{
"code": null,
"e": 6825,
"s": 6658,
"text": "Note that size of the original image is 600 x 960. We need to resize this to our specification of 227 x 227. Calling our earlier-defined resizefunction does this job."
},
{
"code": null,
"e": 6995,
"s": 6825,
"text": "img = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after resizing: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Resized image')\n"
},
{
"code": null,
"e": 7026,
"s": 6995,
"text": "The output is as given below −"
},
{
"code": null,
"e": 7203,
"s": 7026,
"text": "Note that now the image size is 227 x 363. We need to crop this to 227 x 227 for the final feed to our algorithm. We call the previously-defined crop function for this purpose."
},
{
"code": null,
"e": 7378,
"s": 7203,
"text": "img = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after cropping: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Center Cropped')\n"
},
{
"code": null,
"e": 7422,
"s": 7378,
"text": "Below mentioned is the output of the code −"
},
{
"code": null,
"e": 7589,
"s": 7422,
"text": "At this point, the image is of size 227 x 227 and is ready for further processing. We now swap the image axes to extract the three colours into three different zones."
},
{
"code": null,
"e": 7669,
"s": 7589,
"text": "img = img.swapaxes(1, 2).swapaxes(0, 1)\nprint(\"CHW Image Shape: \" , img.shape)\n"
},
{
"code": null,
"e": 7697,
"s": 7669,
"text": "Given below is the output −"
},
{
"code": null,
"e": 7729,
"s": 7697,
"text": "CHW Image Shape: (3, 227, 227)\n"
},
{
"code": null,
"e": 7865,
"s": 7729,
"text": "Note that the last axis has now become the first dimension in the array. We will now plot the three channels using the following code −"
},
{
"code": null,
"e": 8019,
"s": 7865,
"text": "pyplot.figure()\nfor i in range(3):\n pyplot.subplot(1, 3, i+1)\n pyplot.imshow(img[i])\n pyplot.axis('off')\n pyplot.title('RGB channel %d' % (i+1))\n"
},
{
"code": null,
"e": 8048,
"s": 8019,
"text": "The output is stated below −"
},
{
"code": null,
"e": 8271,
"s": 8048,
"text": "Finally, we do some additional processing on the image such as converting Red Green Blue to Blue Green Red (RGB to BGR), removing mean for better results and adding batch size axis using the following three lines of code −"
},
{
"code": null,
"e": 8430,
"s": 8271,
"text": "# convert RGB --> BGR\nimg = img[(2, 1, 0), :, :]\n# remove mean\nimg = img * 255 - mean\n# add batch size axis\nimg = img[np.newaxis, :, :, :].astype(np.float32)\n"
},
{
"code": null,
"e": 8613,
"s": 8430,
"text": "At this point, your image is in NCHW format and is ready for feeding into our network. Next, we will load our pre-trained model files and feed the above image into it for prediction."
},
{
"code": null,
"e": 8716,
"s": 8613,
"text": "We first setup the paths for the init and predict networks defined in the pre-trained models of Caffe."
},
{
"code": null,
"e": 8864,
"s": 8716,
"text": "Remember from our earlier discussion, all the pre-trained models are installed in the models folder. We set up the path to this folder as follows −"
},
{
"code": null,
"e": 8962,
"s": 8864,
"text": "CAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\n"
},
{
"code": null,
"e": 9048,
"s": 8962,
"text": "We set up the path to the init_net protobuf file of the squeezenet model as follows −"
},
{
"code": null,
"e": 9116,
"s": 9048,
"text": "INIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\n"
},
{
"code": null,
"e": 9186,
"s": 9116,
"text": "Likewise, we set up the path to the predict_net protobuf as follows −"
},
{
"code": null,
"e": 9260,
"s": 9186,
"text": "PREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\n"
},
{
"code": null,
"e": 9307,
"s": 9260,
"text": "We print the two paths for diagnosis purpose −"
},
{
"code": null,
"e": 9343,
"s": 9307,
"text": "print(INIT_NET)\nprint(PREDICT_NET)\n"
},
{
"code": null,
"e": 9421,
"s": 9343,
"text": "The above code along with the output is given here for your quick reference −"
},
{
"code": null,
"e": 9694,
"s": 9421,
"text": "CAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\nINIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\nPREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\nprint(INIT_NET)\nprint(PREDICT_NET)\n"
},
{
"code": null,
"e": 9726,
"s": 9694,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 9896,
"s": 9726,
"text": "/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/init_net.pb\n/anaconda3/lib/python3.7/site-packages/caffe2/python/models/squeezenet/predict_net.pb\n"
},
{
"code": null,
"e": 9930,
"s": 9896,
"text": "Next, we will create a predictor."
},
{
"code": null,
"e": 9991,
"s": 9930,
"text": "We read the model files using the following two statements −"
},
{
"code": null,
"e": 10108,
"s": 9991,
"text": "with open(INIT_NET, \"rb\") as f:\n init_net = f.read()\nwith open(PREDICT_NET, \"rb\") as f:\n predict_net = f.read()\n"
},
{
"code": null,
"e": 10211,
"s": 10108,
"text": "The predictor is created by passing pointers to the two files as parameters to the Predictor function."
},
{
"code": null,
"e": 10259,
"s": 10211,
"text": "p = workspace.Predictor(init_net, predict_net)\n"
},
{
"code": null,
"e": 10452,
"s": 10259,
"text": "The p object is the predictor, which is used for predicting the objects in any given image. Note that each input image must be in NCHW format as what we have done earlier to our tree.jpg file."
},
{
"code": null,
"e": 10631,
"s": 10452,
"text": "To predict the objects in a given image is trivial - just executing a single line of command. We call run method on the predictor object for an object detection in a given image."
},
{
"code": null,
"e": 10663,
"s": 10631,
"text": "results = p.run({'data': img})\n"
},
{
"code": null,
"e": 10777,
"s": 10663,
"text": "The prediction results are now available in the results object, which we convert to an array for our readability."
},
{
"code": null,
"e": 10808,
"s": 10777,
"text": "results = np.asarray(results)\n"
},
{
"code": null,
"e": 10897,
"s": 10808,
"text": "Print the dimensions of the array for your understanding using the following statement −"
},
{
"code": null,
"e": 10938,
"s": 10897,
"text": "print(\"results shape: \", results.shape)\n"
},
{
"code": null,
"e": 10969,
"s": 10938,
"text": "The output is as shown below −"
},
{
"code": null,
"e": 11004,
"s": 10969,
"text": "results shape: (1, 1, 1000, 1, 1)\n"
},
{
"code": null,
"e": 11046,
"s": 11004,
"text": "We will now remove the unnecessary axis −"
},
{
"code": null,
"e": 11075,
"s": 11046,
"text": "preds = np.squeeze(results)\n"
},
{
"code": null,
"e": 11164,
"s": 11075,
"text": "The topmost predication can now be retrieved by taking the max value in the preds array."
},
{
"code": null,
"e": 11304,
"s": 11164,
"text": "curr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))\nprint(\"Prediction: \", curr_pred)\nprint(\"Confidence: \", curr_conf)\n"
},
{
"code": null,
"e": 11331,
"s": 11304,
"text": "The output is as follows −"
},
{
"code": null,
"e": 11371,
"s": 11331,
"text": "Prediction: 984\nConfidence: 0.89235985\n"
},
{
"code": null,
"e": 11761,
"s": 11371,
"text": "As you see the model has predicted an object with an index value 984 with 89% confidence. The index of 984 does not make much sense to us in understanding what kind of object is detected. We need to get the stringified name for the object using its index value. The kind of objects that the model recognizes along with their corresponding index values are available on a github repository."
},
{
"code": null,
"e": 11845,
"s": 11761,
"text": "Now, we will see how to retrieve the name for our object having index value of 984."
},
{
"code": null,
"e": 11906,
"s": 11845,
"text": "We create a URL object to the github repository as follows −"
},
{
"code": null,
"e": 12058,
"s": 11906,
"text": "codes = \"https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac0\n71eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes\"\n"
},
{
"code": null,
"e": 12092,
"s": 12058,
"text": "We read the contents of the URL −"
},
{
"code": null,
"e": 12127,
"s": 12092,
"text": "response = urllib2.urlopen(codes)\n"
},
{
"code": null,
"e": 12282,
"s": 12127,
"text": "The response will contain a list of all codes and its descriptions. Few lines of the response are shown below for your understanding of what it contains −"
},
{
"code": null,
"e": 12443,
"s": 12282,
"text": "5: 'electric ray, crampfish, numbfish, torpedo',\n6: 'stingray',\n7: 'cock',\n8: 'hen',\n9: 'ostrich, Struthio camelus',\n10: 'brambling, Fringilla montifringilla',\n"
},
{
"code": null,
"e": 12539,
"s": 12443,
"text": "We now iterate the entire array to locate our desired code of 984 using a for loop as follows −"
},
{
"code": null,
"e": 12842,
"s": 12539,
"text": "for line in response:\n mystring = line.decode('ascii')\n code, result = mystring.partition(\":\")[::2]\n code = code.strip()\n result = result.replace(\"'\", \"\")\n if (code == str(curr_pred)):\n name = result.split(\",\")[0][1:]\n print(\"Model predicts\", name, \"with\", curr_conf, \"confidence\")\n"
},
{
"code": null,
"e": 12901,
"s": 12842,
"text": "When you run the code, you will see the following output −"
},
{
"code": null,
"e": 12953,
"s": 12901,
"text": "Model predicts rapeseed with 0.89235985 confidence\n"
},
{
"code": null,
"e": 12997,
"s": 12953,
"text": "You may now try the model on another image."
},
{
"code": null,
"e": 13258,
"s": 12997,
"text": "To predict another image, simply copy the image file into the images folder of your project directory. This is the directory in which our earlier tree.jpg file is stored. Change the name of the image file in the code. Only one change is required as shown below"
},
{
"code": null,
"e": 13346,
"s": 13258,
"text": "img = skimage.img_as_float(skimage.io.imread(\"images/pretzel.jpg\")).astype(np.float32)\n"
},
{
"code": null,
"e": 13411,
"s": 13346,
"text": "The original picture and the prediction result are shown below −"
},
{
"code": null,
"e": 13443,
"s": 13411,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 13494,
"s": 13443,
"text": "Model predicts pretzel with 0.99999976 confidence\n"
},
{
"code": null,
"e": 13603,
"s": 13494,
"text": "As you see the pre-trained model is able to detect objects in a given image with a great amount of accuracy."
},
{
"code": null,
"e": 13751,
"s": 13603,
"text": "The full source for the above code that uses a pre-trained model for object detection in a given image is mentioned here for your quick reference −"
},
{
"code": null,
"e": 16024,
"s": 13751,
"text": "def crop_image(img,cropx,cropy):\n y,x,c = img.shape\n startx = x//2-(cropx//2)\n starty = y//2-(cropy//2)\n return img[starty:starty+cropy,startx:startx+cropx]\nimg = skimage.img_as_float(skimage.io.imread(\"images/pretzel.jpg\")).astype(np.float32)\nprint(\"Original Image Shape: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Original image')\nimg = resize(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after resizing: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Resized image')\nimg = crop_image(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE)\nprint(\"Image Shape after cropping: \" , img.shape)\npyplot.figure()\npyplot.imshow(img)\npyplot.title('Center Cropped')\nimg = img.swapaxes(1, 2).swapaxes(0, 1)\nprint(\"CHW Image Shape: \" , img.shape)\npyplot.figure()\nfor i in range(3):\npyplot.subplot(1, 3, i+1)\npyplot.imshow(img[i])\npyplot.axis('off')\npyplot.title('RGB channel %d' % (i+1))\n# convert RGB --> BGR\nimg = img[(2, 1, 0), :, :]\n# remove mean\nimg = img * 255 - mean\n# add batch size axis\nimg = img[np.newaxis, :, :, :].astype(np.float32)\nCAFFE_MODELS = os.path.expanduser(\"/anaconda3/lib/python3.7/site-packages/caffe2/python/models\")\nINIT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'init_net.pb')\nPREDICT_NET = os.path.join(CAFFE_MODELS, 'squeezenet', 'predict_net.pb')\nprint(INIT_NET)\nprint(PREDICT_NET)\nwith open(INIT_NET, \"rb\") as f:\n init_net = f.read()\nwith open(PREDICT_NET, \"rb\") as f:\n predict_net = f.read()\np = workspace.Predictor(init_net, predict_net)\nresults = p.run({'data': img})\nresults = np.asarray(results)\nprint(\"results shape: \", results.shape)\npreds = np.squeeze(results)\ncurr_pred, curr_conf = max(enumerate(preds), key=operator.itemgetter(1))\nprint(\"Prediction: \", curr_pred)\nprint(\"Confidence: \", curr_conf)\ncodes = \"https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes\"\nresponse = urllib2.urlopen(codes)\nfor line in response:\n mystring = line.decode('ascii')\n code, result = mystring.partition(\":\")[::2]\n code = code.strip()\n result = result.replace(\"'\", \"\")\n if (code == str(curr_pred)):\n name = result.split(\",\")[0][1:]\n print(\"Model predicts\", name, \"with\", curr_conf, \"confidence\")\n"
},
{
"code": null,
"e": 16121,
"s": 16024,
"text": "By this time, you know how to use a pre-trained model for doing the predictions on your dataset."
},
{
"code": null,
"e": 16299,
"s": 16121,
"text": "What’s next is to learn how to define your neural network (NN) architectures in Caffe2 and train them on your dataset. We will now learn how to create a trivial single layer NN."
},
{
"code": null,
"e": 16306,
"s": 16299,
"text": " Print"
},
{
"code": null,
"e": 16317,
"s": 16306,
"text": " Add Notes"
}
]
|
How to call a static constructor or when static constructor is called in C#? | Static constructor are called automatically before the first instance is created or any static members are referenced.
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only.
In c#, only one static constructor is allowed to create
Static constructors have the following properties −
A static constructor does not take access modifiers or have parameters.
A static constructor does not take access modifiers or have parameters.
A class or struct can only have one static constructor.
A class or struct can only have one static constructor.
Static constructors cannot be inherited or overloaded.
Static constructors cannot be inherited or overloaded.
A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
The user has no control on when the static constructor is executed in the program.
class Program{
static Program(){
// Your Code
}
static void Main(){
Console.ReadLine();
}
} | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Static constructor are called automatically before the first instance is created or any static members are referenced."
},
{
"code": null,
"e": 1313,
"s": 1181,
"text": "A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only."
},
{
"code": null,
"e": 1369,
"s": 1313,
"text": "In c#, only one static constructor is allowed to create"
},
{
"code": null,
"e": 1421,
"s": 1369,
"text": "Static constructors have the following properties −"
},
{
"code": null,
"e": 1493,
"s": 1421,
"text": "A static constructor does not take access modifiers or have parameters."
},
{
"code": null,
"e": 1565,
"s": 1493,
"text": "A static constructor does not take access modifiers or have parameters."
},
{
"code": null,
"e": 1621,
"s": 1565,
"text": "A class or struct can only have one static constructor."
},
{
"code": null,
"e": 1677,
"s": 1621,
"text": "A class or struct can only have one static constructor."
},
{
"code": null,
"e": 1732,
"s": 1677,
"text": "Static constructors cannot be inherited or overloaded."
},
{
"code": null,
"e": 1787,
"s": 1732,
"text": "Static constructors cannot be inherited or overloaded."
},
{
"code": null,
"e": 1932,
"s": 1787,
"text": "A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically."
},
{
"code": null,
"e": 2077,
"s": 1932,
"text": "A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically."
},
{
"code": null,
"e": 2160,
"s": 2077,
"text": "The user has no control on when the static constructor is executed in the program."
},
{
"code": null,
"e": 2276,
"s": 2160,
"text": "class Program{\n static Program(){\n // Your Code\n }\n static void Main(){\n Console.ReadLine();\n }\n}"
}
]
|
Print the alternate nodes of linked list (Iterative Method) - GeeksforGeeks | 14 Feb, 2020
Given a linked list, print the alternate nodes of linked list.
Examples:
Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42
Output : 1 -> 3 -> 17 -> 29
Alternate nodes : 1 -> 3 -> 17 -> 29
Input : 10 -> 17 -> 33 -> 38 -> 73
Output : 10 -> 33 -> 73
Alternate nodes : 10 -> 33 -> 73
Approach :1. Traverse the whole linked list.2. Set count = 0.3. Print node when count is even.4. Visit the next node.
C++
C
Java
Python3
C#
// CPP code to print Alternate Nodes #include <iostream>using namespace std; /* Link list node */struct Node{ int data; struct Node* next; }; /* Function to get the alternate nodes of the linked list */void printAlternateNode(struct Node* head) { int count = 0; while (head != NULL) { // when count is even print the nodes if (count % 2 == 0) cout << head->data << " "; // count the nodes count++; // move on the next node. head = head->next; } } // Function to push node at head void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } // Driver code int main() { /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); printAlternateNode(head); return 0; } // This code is contributed by shubhamsingh10
// C code to print Alternate Nodes#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the alternate nodes of the linked list */void printAlternateNode(struct Node* head){ int count = 0; while (head != NULL) { // when count is even print the nodes if (count % 2 == 0) printf(" %d ", head->data); // count the nodes count++; // move on the next node. head = head->next; }} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); printAlternateNode(head); return 0;}
// Java code to print Alternate Nodes class GFG{ /* Link list node */static class Node{ int data; Node next; }; /* Function to get the alternate nodes of the linked list */static void printAlternateNode( Node head) { int count = 0; while (head != null) { // when count is even print the nodes if (count % 2 == 0) System.out.printf(" %d ", head.data); // count the nodes count++; // move on the next node. head = head.next; } } // Function to push node at head static Node push( Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Driver code public static void main(String args[]) { /* Start with the empty list */ Node head = null; /* Use push() function to con the below list 8 . 23 . 11 . 29 . 12 */ head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); printAlternateNode(head); }} // This code is contributed by Arnab Kundu
# Python3 code to print Alternate Nodes # Link list nodeclass Node : def __init__(self, data = None) : self.data = data self.next = None # Function to push node at head def push(self, data) : new = Node(data) new.next = self return new # Function to get the alternate # nodes of the linked list def printAlternateNode(self) : head = self while head and head.next != None : print(head.data, end = " ") head = head.next.next # Driver Code node = Node() # Use push() function to construct# the below list 8 -> 23 -> 11 -> 29 -> 12node = node.push(12)node = node.push(29)node = node.push(11)node = node.push(23)node = node.push(8) node.printAlternateNode()
// C# code to print Alternate Nodesusing System; class GFG { /* Link list node */public class Node { public int data; public Node next; }; /* Function to get the alternate nodes of the linked list */static void printAlternateNode( Node head) { int count = 0; while (head != null) { // when count is even print the nodes if (count % 2 == 0) Console.Write(" {0} ", head.data); // count the nodes count++; // move on the next node. head = head.next; } } // Function to push node at head static Node push( Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String []args) { /* Start with the empty list */ Node head = null; /* Use push() function to con the below list 8 . 23 . 11 . 29 . 12 */ head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); printAlternateNode(head); } } // This code has been contributed by 29AjayKumar
8 11 12
Time Complexity : O(n)Auxiliary Space : O(1)
Asked in : Govivace
andrew1234
29AjayKumar
SHUBHAMSINGH10
Govivace
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List vs Array
Delete a Linked List node at a given position
Queue - Linked List Implementation
Implement a stack using singly linked list
Circular Linked List | Set 1 (Introduction and Applications)
Implementing a Linked List in Java using Class
Remove duplicates from a sorted linked list
Find Length of a Linked List (Iterative and Recursive)
Function to check if a singly linked list is palindrome
Top 20 Linked List Interview Question | [
{
"code": null,
"e": 25020,
"s": 24992,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 25083,
"s": 25020,
"text": "Given a linked list, print the alternate nodes of linked list."
},
{
"code": null,
"e": 25093,
"s": 25083,
"text": "Examples:"
},
{
"code": null,
"e": 25302,
"s": 25093,
"text": "Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42\nOutput : 1 -> 3 -> 17 -> 29\nAlternate nodes : 1 -> 3 -> 17 -> 29\n\nInput : 10 -> 17 -> 33 -> 38 -> 73\nOutput : 10 -> 33 -> 73\nAlternate nodes : 10 -> 33 -> 73\n"
},
{
"code": null,
"e": 25420,
"s": 25302,
"text": "Approach :1. Traverse the whole linked list.2. Set count = 0.3. Print node when count is even.4. Visit the next node."
},
{
"code": null,
"e": 25424,
"s": 25420,
"text": "C++"
},
{
"code": null,
"e": 25426,
"s": 25424,
"text": "C"
},
{
"code": null,
"e": 25431,
"s": 25426,
"text": "Java"
},
{
"code": null,
"e": 25439,
"s": 25431,
"text": "Python3"
},
{
"code": null,
"e": 25442,
"s": 25439,
"text": "C#"
},
{
"code": "// CPP code to print Alternate Nodes #include <iostream>using namespace std; /* Link list node */struct Node{ int data; struct Node* next; }; /* Function to get the alternate nodes of the linked list */void printAlternateNode(struct Node* head) { int count = 0; while (head != NULL) { // when count is even print the nodes if (count % 2 == 0) cout << head->data << \" \"; // count the nodes count++; // move on the next node. head = head->next; } } // Function to push node at head void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } // Driver code int main() { /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); printAlternateNode(head); return 0; } // This code is contributed by shubhamsingh10",
"e": 26629,
"s": 25442,
"text": null
},
{
"code": "// C code to print Alternate Nodes#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Function to get the alternate nodes of the linked list */void printAlternateNode(struct Node* head){ int count = 0; while (head != NULL) { // when count is even print the nodes if (count % 2 == 0) printf(\" %d \", head->data); // count the nodes count++; // move on the next node. head = head->next; }} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); printAlternateNode(head); return 0;}",
"e": 27732,
"s": 26629,
"text": null
},
{
"code": "// Java code to print Alternate Nodes class GFG{ /* Link list node */static class Node{ int data; Node next; }; /* Function to get the alternate nodes of the linked list */static void printAlternateNode( Node head) { int count = 0; while (head != null) { // when count is even print the nodes if (count % 2 == 0) System.out.printf(\" %d \", head.data); // count the nodes count++; // move on the next node. head = head.next; } } // Function to push node at head static Node push( Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Driver code public static void main(String args[]) { /* Start with the empty list */ Node head = null; /* Use push() function to con the below list 8 . 23 . 11 . 29 . 12 */ head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); printAlternateNode(head); }} // This code is contributed by Arnab Kundu",
"e": 28891,
"s": 27732,
"text": null
},
{
"code": "# Python3 code to print Alternate Nodes # Link list nodeclass Node : def __init__(self, data = None) : self.data = data self.next = None # Function to push node at head def push(self, data) : new = Node(data) new.next = self return new # Function to get the alternate # nodes of the linked list def printAlternateNode(self) : head = self while head and head.next != None : print(head.data, end = \" \") head = head.next.next # Driver Code node = Node() # Use push() function to construct# the below list 8 -> 23 -> 11 -> 29 -> 12node = node.push(12)node = node.push(29)node = node.push(11)node = node.push(23)node = node.push(8) node.printAlternateNode()",
"e": 29704,
"s": 28891,
"text": null
},
{
"code": "// C# code to print Alternate Nodesusing System; class GFG { /* Link list node */public class Node { public int data; public Node next; }; /* Function to get the alternate nodes of the linked list */static void printAlternateNode( Node head) { int count = 0; while (head != null) { // when count is even print the nodes if (count % 2 == 0) Console.Write(\" {0} \", head.data); // count the nodes count++; // move on the next node. head = head.next; } } // Function to push node at head static Node push( Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String []args) { /* Start with the empty list */ Node head = null; /* Use push() function to con the below list 8 . 23 . 11 . 29 . 12 */ head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); printAlternateNode(head); } } // This code has been contributed by 29AjayKumar",
"e": 30899,
"s": 29704,
"text": null
},
{
"code": null,
"e": 30910,
"s": 30899,
"text": "8 11 12\n"
},
{
"code": null,
"e": 30955,
"s": 30910,
"text": "Time Complexity : O(n)Auxiliary Space : O(1)"
},
{
"code": null,
"e": 30975,
"s": 30955,
"text": "Asked in : Govivace"
},
{
"code": null,
"e": 30986,
"s": 30975,
"text": "andrew1234"
},
{
"code": null,
"e": 30998,
"s": 30986,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31013,
"s": 30998,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 31022,
"s": 31013,
"text": "Govivace"
},
{
"code": null,
"e": 31034,
"s": 31022,
"text": "Linked List"
},
{
"code": null,
"e": 31046,
"s": 31034,
"text": "Linked List"
},
{
"code": null,
"e": 31144,
"s": 31046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31165,
"s": 31144,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 31211,
"s": 31165,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 31246,
"s": 31211,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 31289,
"s": 31246,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 31350,
"s": 31289,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 31397,
"s": 31350,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 31441,
"s": 31397,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 31496,
"s": 31441,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 31552,
"s": 31496,
"text": "Function to check if a singly linked list is palindrome"
}
]
|
CSS border-style Property - GeeksforGeeks | 02 Nov, 2021
The border-style CSS property is a shorthand property that sets the line style for all four sides of an element’s border.
Note: The border-style property can take One to Four values at a time.
Syntax:
border-style: value;
Default Value
none
Property Values:
none: No border is created and it is left plain.
hidden: Just like none, it doesn’t show any border unless a background image is added, then the border-top-width will be set to 0 irrespective of the user-defined value.
dotted: A series of dots are displayed in a line as the border.
solid: A single solid and bold line is used as a border.
dashed: A series of square dashed lines are used as a border.
double: Two lines placed parallel to each other act as the border.
groove: Displays a 3D grooved border, its effect depends on border-color value.
ridge: Displays a 3D ridged border, its effect depends on border-color value.
inset: displays a 3D inset border, its effect depends on border-color value.
outset: Displays a 3D outset border, its effect depends on border-color value.
The border-style property is a shorthand for the following CSS properties:
CSS border-bottom-style Property: It s used to set the style of the bottom border of an element.
CSS border-top-style Property: It is used to specify the style of the top border.
CSS border-left-style Property: It is used to set the style of the left border of an element.
CSS border-right-style Property: It is used to change the appearance of the right line segment of the border of an element.
CSS border-block-style Property: It is used to set the individual logical block border-style property values in a single place in the style sheet.
CSS border-inline-style Property: It is an inbuilt property in CSS which is used to set the individual logical block inline-border-style property values in a single place in the style sheet.
The border-style property may be defined by using one, two, three, or four values, as given below:
If a single value is assigned, it will set the style for all 4 sides.
If two values are assigned, the first style is set to the top and bottom sides and the second will be set to the left & right sides.
If three values are assigned, the first style is set to the top, the second is set to the left and right, the third is set to the bottom.
If four-style values are assigned, the styles are set to the top, right, bottom, and left, which follows the clockwise order.
The below examples illustrate the use of the border-style property.
Example 1: This example is using only one value for all borders.
HTML
<!DOCTYPE html><html><head> <title>Dotted Borders</title> <style> .GFG { border-style: dotted; border-width: 6px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> </div></body></html>
Output:
Example 2: This example is using multiple values for borders.
HTML
<!DOCTYPE html><html><head> <title>Dotted Borders</title> <style> .GFG { border-style: solid double dashed dotted; border-width: 6px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class="GFG"> <h2>GeeksforGeeks</h2> </div></body></html>
Output:
Supported Browser: The browser supported by border-style Property are listed below:
Chrome 1.0
Edge 12.0
IE 4.0
Firefox 1.0
Safari 1.0
Opera 3.5
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
ManasChhabra2
CSS-Properties
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 24917,
"s": 24889,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 25039,
"s": 24917,
"text": "The border-style CSS property is a shorthand property that sets the line style for all four sides of an element’s border."
},
{
"code": null,
"e": 25110,
"s": 25039,
"text": "Note: The border-style property can take One to Four values at a time."
},
{
"code": null,
"e": 25118,
"s": 25110,
"text": "Syntax:"
},
{
"code": null,
"e": 25139,
"s": 25118,
"text": "border-style: value;"
},
{
"code": null,
"e": 25154,
"s": 25139,
"text": "Default Value "
},
{
"code": null,
"e": 25159,
"s": 25154,
"text": "none"
},
{
"code": null,
"e": 25176,
"s": 25159,
"text": "Property Values:"
},
{
"code": null,
"e": 25225,
"s": 25176,
"text": "none: No border is created and it is left plain."
},
{
"code": null,
"e": 25395,
"s": 25225,
"text": "hidden: Just like none, it doesn’t show any border unless a background image is added, then the border-top-width will be set to 0 irrespective of the user-defined value."
},
{
"code": null,
"e": 25459,
"s": 25395,
"text": "dotted: A series of dots are displayed in a line as the border."
},
{
"code": null,
"e": 25516,
"s": 25459,
"text": "solid: A single solid and bold line is used as a border."
},
{
"code": null,
"e": 25578,
"s": 25516,
"text": "dashed: A series of square dashed lines are used as a border."
},
{
"code": null,
"e": 25645,
"s": 25578,
"text": "double: Two lines placed parallel to each other act as the border."
},
{
"code": null,
"e": 25725,
"s": 25645,
"text": "groove: Displays a 3D grooved border, its effect depends on border-color value."
},
{
"code": null,
"e": 25803,
"s": 25725,
"text": "ridge: Displays a 3D ridged border, its effect depends on border-color value."
},
{
"code": null,
"e": 25880,
"s": 25803,
"text": "inset: displays a 3D inset border, its effect depends on border-color value."
},
{
"code": null,
"e": 25959,
"s": 25880,
"text": "outset: Displays a 3D outset border, its effect depends on border-color value."
},
{
"code": null,
"e": 26034,
"s": 25959,
"text": "The border-style property is a shorthand for the following CSS properties:"
},
{
"code": null,
"e": 26131,
"s": 26034,
"text": "CSS border-bottom-style Property: It s used to set the style of the bottom border of an element."
},
{
"code": null,
"e": 26213,
"s": 26131,
"text": "CSS border-top-style Property: It is used to specify the style of the top border."
},
{
"code": null,
"e": 26307,
"s": 26213,
"text": "CSS border-left-style Property: It is used to set the style of the left border of an element."
},
{
"code": null,
"e": 26431,
"s": 26307,
"text": "CSS border-right-style Property: It is used to change the appearance of the right line segment of the border of an element."
},
{
"code": null,
"e": 26578,
"s": 26431,
"text": "CSS border-block-style Property: It is used to set the individual logical block border-style property values in a single place in the style sheet."
},
{
"code": null,
"e": 26769,
"s": 26578,
"text": "CSS border-inline-style Property: It is an inbuilt property in CSS which is used to set the individual logical block inline-border-style property values in a single place in the style sheet."
},
{
"code": null,
"e": 26868,
"s": 26769,
"text": "The border-style property may be defined by using one, two, three, or four values, as given below:"
},
{
"code": null,
"e": 26938,
"s": 26868,
"text": "If a single value is assigned, it will set the style for all 4 sides."
},
{
"code": null,
"e": 27071,
"s": 26938,
"text": "If two values are assigned, the first style is set to the top and bottom sides and the second will be set to the left & right sides."
},
{
"code": null,
"e": 27209,
"s": 27071,
"text": "If three values are assigned, the first style is set to the top, the second is set to the left and right, the third is set to the bottom."
},
{
"code": null,
"e": 27335,
"s": 27209,
"text": "If four-style values are assigned, the styles are set to the top, right, bottom, and left, which follows the clockwise order."
},
{
"code": null,
"e": 27403,
"s": 27335,
"text": "The below examples illustrate the use of the border-style property."
},
{
"code": null,
"e": 27469,
"s": 27403,
"text": "Example 1: This example is using only one value for all borders. "
},
{
"code": null,
"e": 27474,
"s": 27469,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Dotted Borders</title> <style> .GFG { border-style: dotted; border-width: 6px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> </div></body></html>",
"e": 27834,
"s": 27474,
"text": null
},
{
"code": null,
"e": 27842,
"s": 27834,
"text": "Output:"
},
{
"code": null,
"e": 27904,
"s": 27842,
"text": "Example 2: This example is using multiple values for borders."
},
{
"code": null,
"e": 27909,
"s": 27904,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Dotted Borders</title> <style> .GFG { border-style: solid double dashed dotted; border-width: 6px; background: #009900; padding: 30px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <div class=\"GFG\"> <h2>GeeksforGeeks</h2> </div></body></html>",
"e": 28289,
"s": 27909,
"text": null
},
{
"code": null,
"e": 28297,
"s": 28289,
"text": "Output:"
},
{
"code": null,
"e": 28382,
"s": 28297,
"text": "Supported Browser: The browser supported by border-style Property are listed below: "
},
{
"code": null,
"e": 28393,
"s": 28382,
"text": "Chrome 1.0"
},
{
"code": null,
"e": 28403,
"s": 28393,
"text": "Edge 12.0"
},
{
"code": null,
"e": 28410,
"s": 28403,
"text": "IE 4.0"
},
{
"code": null,
"e": 28422,
"s": 28410,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 28433,
"s": 28422,
"text": "Safari 1.0"
},
{
"code": null,
"e": 28443,
"s": 28433,
"text": "Opera 3.5"
},
{
"code": null,
"e": 28580,
"s": 28443,
"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": 28601,
"s": 28580,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 28615,
"s": 28601,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28630,
"s": 28615,
"text": "CSS-Properties"
},
{
"code": null,
"e": 28637,
"s": 28630,
"text": "Picked"
},
{
"code": null,
"e": 28641,
"s": 28637,
"text": "CSS"
},
{
"code": null,
"e": 28646,
"s": 28641,
"text": "HTML"
},
{
"code": null,
"e": 28663,
"s": 28646,
"text": "Web Technologies"
},
{
"code": null,
"e": 28668,
"s": 28663,
"text": "HTML"
},
{
"code": null,
"e": 28766,
"s": 28668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28816,
"s": 28766,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28878,
"s": 28816,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28926,
"s": 28878,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28984,
"s": 28926,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29039,
"s": 28984,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29089,
"s": 29039,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29151,
"s": 29089,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29199,
"s": 29151,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29259,
"s": 29199,
"text": "How to set the default value for an HTML <select> element ?"
}
]
|
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks | 28 Jun, 2021
Host A sends a UDP datagram containing 8880 bytes of user data to host B over an Ethernet LAN. Ethernet frames may carry data up to 1500 bytes (i.e. MTU = 1500 bytes). Size of UDP header is 8 bytes and size of IP header is 20 bytes. There is no option field in IP header. How may total number of IP fragments will be transmitted and what will be the contents of offset field in the last fragment?(A) 6 and 925(B) 6 and 7400(C) 7 and 1110(D) 7 and 8880Answer: (C)Explanation:
UDP data = 8880 bytes
UDP header = 8 bytes
IP Header = 20 bytes
Total Size excluding IP Header = 8888 bytes.
Number of fragments = ⌈ 8888 / 1480 ⌉
= 7
Refer the Kurose book slides on IP (Offset is always scaled by 8)
Offset of last segment = (1480 * 6) / 8 = 1110
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25579,
"s": 25551,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26054,
"s": 25579,
"text": "Host A sends a UDP datagram containing 8880 bytes of user data to host B over an Ethernet LAN. Ethernet frames may carry data up to 1500 bytes (i.e. MTU = 1500 bytes). Size of UDP header is 8 bytes and size of IP header is 20 bytes. There is no option field in IP header. How may total number of IP fragments will be transmitted and what will be the contents of offset field in the last fragment?(A) 6 and 925(B) 6 and 7400(C) 7 and 1110(D) 7 and 8880Answer: (C)Explanation:"
},
{
"code": null,
"e": 26345,
"s": 26054,
"text": "UDP data = 8880 bytes\nUDP header = 8 bytes\nIP Header = 20 bytes\n\nTotal Size excluding IP Header = 8888 bytes.\n\nNumber of fragments = ⌈ 8888 / 1480 ⌉ \n = 7\nRefer the Kurose book slides on IP (Offset is always scaled by 8)\n\nOffset of last segment = (1480 * 6) / 8 = 1110 "
},
{
"code": null,
"e": 26367,
"s": 26345,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26388,
"s": 26367,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26414,
"s": 26388,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26419,
"s": 26414,
"text": "GATE"
},
{
"code": null,
"e": 26517,
"s": 26419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26551,
"s": 26517,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26585,
"s": 26551,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26619,
"s": 26585,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26652,
"s": 26619,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26688,
"s": 26652,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26722,
"s": 26688,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26758,
"s": 26722,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26792,
"s": 26758,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26826,
"s": 26792,
"text": "GATE | GATE-CS-2009 | Question 38"
}
]
|
Text Styles in Android - GeeksforGeeks | 29 Jul, 2021
TextView displays the declared text in a standard way unless the developer specifies particular attributes to make the text appear better. These attributes can directly be declared into the TextView tags. However, in order to maintain a scalable and clean code, industrial practices suggest gathering together all such attributes. Meaning, there can be the same or different styles for different UI elements within the application and all of them need to be grouped into a single file that could be called wherever required. Through this article, we want to show you how you can create styles and apply them to TextViews. In our demonstration, we dynamically changed the TextView style by tapping on it.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Create styles.xml in the res>values folder
To create a styles file, right-click on the value folder inside the res folder, move the cursor to new, and click on Values Resource File.
Now give it the name “styles” and click on OK. You can use any name of your choice. Remember to check if the directory name is values, as our file shall contain attribute values. The generated file will be an XML file.
Once the file is generated, it should appear like this. Now, we can add the styles to this file. Go to the next step to see how you could create a style.
Step 3: Add styles in the styles.xml file
Refer to the below code. We have already declared a few styles for you. It is necessary to give a name to each style. Attributes related to text are declared as items between the style opening and closing tags.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <style name="whiteText"> <item name="android:textStyle">italic</item> <item name="android:textColor">#ffffff</item> </style> <style name="gfgGreenText"> <item name="android:textStyle">bold</item> <item name="android:textColor">#0f9d58</item> </style> </resources>
Step 4: Add colors to change the background of the TextView in the colors.xml file (Optional)
This step is optional. We declared two colors of our interest just to change the TextView background.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <!--There could be a list of colors declared here--> <!--Additionally, we are adding the below two colors--> <color name="gfg_green">#0f9d58</color> <color name="white">#FFFFFFFF</color> </resources>
Step 5: Add a TextView in the layout file (activity_main.xml)
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--TextView--> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="GeeksforGeeks" android:textSize="36sp" android:textStyle="bold" /> </RelativeLayout>
Step 6: Write a program to toggle between the styles on TextView click in the Main code (MainActivity.kt)
Kotlin
import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.annotation.RequiresApiimport org.w3c.dom.Text class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring TextView from the layout val tv1 = findViewById<TextView>(R.id.textView1) // A simple toggle variable that keeps // changing on TextView click/tap var toggle = true // What happens when the // TextView in clicked/tapped tv1.setOnClickListener { // If toggle is true, then text will become // white and background will become green // Else text is green and background is white if(toggle){ tv1.setTextAppearance(R.style.whiteText) tv1.setBackgroundResource(R.color.gfg_green) } else { tv1.setTextAppearance(R.style.gfgGreenText) tv1.setBackgroundResource(R.color.white) } // Logically inversing the toggle, i.e. if toggle // is true then it shall become false // And vice-versa to keep the styles // keep changing on every click/tap toggle = !toggle } }}
Input:
Keep tapping on the TextView to observe the changes.
Output:
We can see that the Text style changes to bold and then Italic along with background color changes. The cycle keeps repeating on every even click/tap.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Kotlin when expression | [
{
"code": null,
"e": 26491,
"s": 26463,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 27195,
"s": 26491,
"text": "TextView displays the declared text in a standard way unless the developer specifies particular attributes to make the text appear better. These attributes can directly be declared into the TextView tags. However, in order to maintain a scalable and clean code, industrial practices suggest gathering together all such attributes. Meaning, there can be the same or different styles for different UI elements within the application and all of them need to be grouped into a single file that could be called wherever required. Through this article, we want to show you how you can create styles and apply them to TextViews. In our demonstration, we dynamically changed the TextView style by tapping on it."
},
{
"code": null,
"e": 27242,
"s": 27195,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 27481,
"s": 27242,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 27532,
"s": 27481,
"text": "Step 2: Create styles.xml in the res>values folder"
},
{
"code": null,
"e": 27671,
"s": 27532,
"text": "To create a styles file, right-click on the value folder inside the res folder, move the cursor to new, and click on Values Resource File."
},
{
"code": null,
"e": 27890,
"s": 27671,
"text": "Now give it the name “styles” and click on OK. You can use any name of your choice. Remember to check if the directory name is values, as our file shall contain attribute values. The generated file will be an XML file."
},
{
"code": null,
"e": 28044,
"s": 27890,
"text": "Once the file is generated, it should appear like this. Now, we can add the styles to this file. Go to the next step to see how you could create a style."
},
{
"code": null,
"e": 28086,
"s": 28044,
"text": "Step 3: Add styles in the styles.xml file"
},
{
"code": null,
"e": 28297,
"s": 28086,
"text": "Refer to the below code. We have already declared a few styles for you. It is necessary to give a name to each style. Attributes related to text are declared as items between the style opening and closing tags."
},
{
"code": null,
"e": 28301,
"s": 28297,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <style name=\"whiteText\"> <item name=\"android:textStyle\">italic</item> <item name=\"android:textColor\">#ffffff</item> </style> <style name=\"gfgGreenText\"> <item name=\"android:textStyle\">bold</item> <item name=\"android:textColor\">#0f9d58</item> </style> </resources>",
"e": 28658,
"s": 28301,
"text": null
},
{
"code": null,
"e": 28752,
"s": 28658,
"text": "Step 4: Add colors to change the background of the TextView in the colors.xml file (Optional)"
},
{
"code": null,
"e": 28854,
"s": 28752,
"text": "This step is optional. We declared two colors of our interest just to change the TextView background."
},
{
"code": null,
"e": 28858,
"s": 28854,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <!--There could be a list of colors declared here--> <!--Additionally, we are adding the below two colors--> <color name=\"gfg_green\">#0f9d58</color> <color name=\"white\">#FFFFFFFF</color> </resources>",
"e": 29125,
"s": 28858,
"text": null
},
{
"code": null,
"e": 29187,
"s": 29125,
"text": "Step 5: Add a TextView in the layout file (activity_main.xml)"
},
{
"code": null,
"e": 29191,
"s": 29187,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--TextView--> <TextView android:id=\"@+id/textView1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"GeeksforGeeks\" android:textSize=\"36sp\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 29794,
"s": 29191,
"text": null
},
{
"code": null,
"e": 29900,
"s": 29794,
"text": "Step 6: Write a program to toggle between the styles on TextView click in the Main code (MainActivity.kt)"
},
{
"code": null,
"e": 29907,
"s": 29900,
"text": "Kotlin"
},
{
"code": "import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.annotation.RequiresApiimport org.w3c.dom.Text class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring TextView from the layout val tv1 = findViewById<TextView>(R.id.textView1) // A simple toggle variable that keeps // changing on TextView click/tap var toggle = true // What happens when the // TextView in clicked/tapped tv1.setOnClickListener { // If toggle is true, then text will become // white and background will become green // Else text is green and background is white if(toggle){ tv1.setTextAppearance(R.style.whiteText) tv1.setBackgroundResource(R.color.gfg_green) } else { tv1.setTextAppearance(R.style.gfgGreenText) tv1.setBackgroundResource(R.color.white) } // Logically inversing the toggle, i.e. if toggle // is true then it shall become false // And vice-versa to keep the styles // keep changing on every click/tap toggle = !toggle } }}",
"e": 31378,
"s": 29907,
"text": null
},
{
"code": null,
"e": 31386,
"s": 31378,
"text": "Input: "
},
{
"code": null,
"e": 31439,
"s": 31386,
"text": "Keep tapping on the TextView to observe the changes."
},
{
"code": null,
"e": 31448,
"s": 31439,
"text": "Output: "
},
{
"code": null,
"e": 31599,
"s": 31448,
"text": "We can see that the Text style changes to bold and then Italic along with background color changes. The cycle keeps repeating on every even click/tap."
},
{
"code": null,
"e": 31607,
"s": 31599,
"text": "Android"
},
{
"code": null,
"e": 31614,
"s": 31607,
"text": "Kotlin"
},
{
"code": null,
"e": 31622,
"s": 31614,
"text": "Android"
},
{
"code": null,
"e": 31720,
"s": 31622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31758,
"s": 31720,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31797,
"s": 31758,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31847,
"s": 31797,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31873,
"s": 31847,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 31915,
"s": 31873,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31934,
"s": 31915,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 31947,
"s": 31934,
"text": "Kotlin Array"
},
{
"code": null,
"e": 31989,
"s": 31947,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32016,
"s": 31989,
"text": "Kotlin Setters and Getters"
}
]
|
How to save a plot as SVG created with ggplot2 in R? | There are multiple ways to save a plot created in R. Base R provides, metafile, bitmap, and postscript options to copy and save the plots created in R but we can also save the plots created with ggplot2 as an SVG file with the help of svglite package. The ggsave function of svglite package does this job easily and we can also define the height and width of the plot inside this function.
Live Demo
Install the svglite package −
install.packages("svglite")
Consider the ToothGrowth data and create a scatterplot between len and dose −
head(ToothGrowth)
len supp dose
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
library(ggplot2)
library(svglite)
ScatterPlotImage<-ggplot(ToothGrowth,aes(len,dose))+geom_point(size=3)
ScatterPlotImage
ggsave(file="Scatter.svg", plot=ScatterPlotImage, width=10, height=10)
This plot will be saved as an SVG in the default folder for your R version as shown above. | [
{
"code": null,
"e": 1455,
"s": 1062,
"text": " There are multiple ways to save a plot created in R. Base R provides, metafile, bitmap, and postscript options to copy and save the plots created in R but we can also save the plots created with ggplot2 as an SVG file with the help of svglite package. The ggsave function of svglite package does this job easily and we can also define the height and width of the plot inside this function."
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": " Live Demo"
},
{
"code": null,
"e": 1496,
"s": 1466,
"text": "Install the svglite package −"
},
{
"code": null,
"e": 1524,
"s": 1496,
"text": "install.packages(\"svglite\")"
},
{
"code": null,
"e": 1602,
"s": 1524,
"text": "Consider the ToothGrowth data and create a scatterplot between len and dose −"
},
{
"code": null,
"e": 1848,
"s": 1602,
"text": "head(ToothGrowth)\n len supp dose\n1 4.2 VC 0.5\n2 11.5 VC 0.5\n3 7.3 VC 0.5\n4 5.8 VC 0.5\n5 6.4 VC 0.5\n6 10.0 VC 0.5\nlibrary(ggplot2)\nlibrary(svglite)\nScatterPlotImage<-ggplot(ToothGrowth,aes(len,dose))+geom_point(size=3)\nScatterPlotImage"
},
{
"code": null,
"e": 1919,
"s": 1848,
"text": "ggsave(file=\"Scatter.svg\", plot=ScatterPlotImage, width=10, height=10)"
},
{
"code": null,
"e": 2010,
"s": 1919,
"text": "This plot will be saved as an SVG in the default folder for your R version as shown above."
}
]
|
Minimum edges required to add to make Euler Circuit | 28 Nov, 2021
Given a undirected graph of n nodes and m edges. The task is to find minimum edges required to make Euler Circuit in the given graph.
Examples:
Input : n = 3,
m = 2
Edges[] = {{1, 2}, {2, 3}}
Output : 1
By connecting 1 to 3, we can create a Euler Circuit.
For a Euler Circuit to exist in the graph we require that every node should have even degree because then there exists an edge that can be used to exit the node after entering it.
Now, there can be two case:1. There is one connected component in the graphIn this case, if all the nodes in the graph is of even degree then we say that the graph already have a Euler Circuit and we don’t need to add any edge in it. But if there is any node with odd degree we need to add edges.There can be even number of odd degree vertices in the graph. This can be easily proved by the fact that the sum of degrees from the even degrees node and degrees from odd degrees node should match the total degrees that is always even as every edge contributes two to this sum. Now, if we pair up random odd degree nodes in the graph and add an edge between them we can make all nodes to have even degree and thus make an Euler Circuit exist.
2. There are disconnected components in the graphWe first mark component as odd and even. Odd components are those which have at least one odd degree node in them. Take all the even components and select a random vertex from every component and line them up linearly. Now we add an edge between adjacent vertices. So we have connected the even components and made an equivalent odd components that has two nodes with odd degree.Now to deal with odd components i.e components with at least one odd degree node. We can connect all these odd components using edges whose number is equal to the number of disconnected components. This can be done by placing the components in the cyclic order and picking two odd degree nodes from every component and using these to connect to the components on either side. Now we have a single connected component for which we have discussed.
Below is implementation of this approach:
C++
Java
Python3
// C++ program to find minimum edge required// to make Euler Circuit#include <bits/stdc++.h>using namespace std; // Depth-First Search to find a connected// componentvoid dfs(vector<int> g[], int vis[], int odd[], int deg[], int comp, int v){ vis[v] = 1; if (deg[v]%2 == 1) odd[comp]++; for (int u : g[v]) if (vis[u] == 0) dfs(g, vis, odd, deg, comp, u);} // Return minimum edge required to make Euler// Circuitint minEdge(int n, int m, int s[], int d[]){ // g : to store adjacency list // representation of graph. // e : to store list of even degree vertices // o : to store list of odd degree vertices vector<int> g[n+1], e, o; int deg[n+1]; // Degrees of vertices int vis[n+1]; // To store visited in DFS int odd[n+1]; // Number of odd nodes in components memset(deg, 0, sizeof(deg)); memset(vis, 0, sizeof(vis)); memset(odd, 0, sizeof(odd)); for (int i = 0; i < m; i++) { g[s[i]].push_back(d[i]); g[d[i]].push_back(s[i]); deg[s[i]]++; deg[d[i]]++; } // 'ans' is result and 'comp' is component id int ans = 0, comp = 0; for (int i = 1; i <= n; i++) { if (vis[i]==0) { comp++; dfs(g, vis, odd, deg, comp, i); // Checking if connected component // is odd. if (odd[comp] == 0) e.push_back(comp); // Checking if connected component // is even. else o.push_back(comp); } } // If whole graph is a single connected // component with even degree. if (o.size() == 0 && e.size() == 1) return 0; // If all connected component is even if (o.size() == 0) return e.size(); // If graph have atleast one even connected // component if (e.size() != 0) ans += e.size(); // For all the odd connected component. for (int i : o) ans += odd[i]/2; return ans;} // Driven Programint main(){ int n = 3, m = 2; int source[] = { 1, 2 }; int destination[] = { 2, 3 }; cout << minEdge(n, m, source, destination) << endl; return 0;}
// Java program to find minimum edge// required to make Euler Circuitimport java.io.*;import java.util.*; class GFG { // Depth-First Search to find // a connected component static void dfs(Vector<Integer>[] g, int[] vis, int[] odd, int[] deg, int comp, int v) { vis[v] = 1; if (deg[v] % 2 == 1) odd[comp]++; for (int u : g[v]) if (vis[u] == 0) dfs(g, vis, odd, deg, comp, u); } // Return minimum edge required // to make Euler Circuit static int minEdge(int n, int m, int[] s, int[] d) { // g : to store adjacency list // representation of graph. // e : to store list of even degree vertices // o : to store list of odd degree vertices @SuppressWarnings("unchecked") Vector<Integer>[] g = new Vector[n + 1]; Vector<Integer> e = new Vector<>(); Vector<Integer> o = new Vector<>(); for (int i = 0; i < n + 1; i++) g[i] = new Vector<>(); // Degrees of vertices int[] deg = new int[n + 1]; // To store visited in DFS int[] vis = new int[n + 1]; // Number of odd nodes in components int[] odd = new int[n + 1]; Arrays.fill(deg, 0); Arrays.fill(vis, 0); Arrays.fill(odd, 0); for (int i = 0; i < m; i++) { g[s[i]].add(d[i]); g[d[i]].add(s[i]); deg[s[i]]++; deg[d[i]]++; } // 'ans' is result and // 'comp' is component id int ans = 0, comp = 0; for (int i = 1; i <= n; i++) { if (vis[i] == 0) { comp++; dfs(g, vis, odd, deg, comp, i); // Checking if connected component // is odd. if (odd[comp] == 0) e.add(comp); // Checking if connected component // is even. else o.add(comp); } } // If whole graph is a single connected // component with even degree. if (o.size() == 0 && e.size() == 1) return 0; // If all connected component is even if (o.size() == 0) return e.size(); // If graph have atleast one // even connected component if (e.size() != 0) ans += e.size(); // For all the odd connected component. for (int i : o) ans += odd[i] / 2; return ans; } // Driver Code public static void main(String[] args) throws IOException { int n = 3, m = 2; int[] source = { 1, 2 }; int[] destination = { 2, 3 }; System.out.println(minEdge(n, m, source, destination)); }} // This code is contributed by// sanjeev2552
# Python3 program to find minimum edge # required to make Euler Circuit # Depth-First Search to find a # connected component def dfs(g, vis, odd, deg, comp, v): vis[v] = 1 if (deg[v] % 2 == 1): odd[comp] += 1 for u in range(len(g[v])): if (vis[u] == 0): dfs(g, vis, odd, deg, comp, u) # Return minimum edge required to# make Euler Circuit def minEdge(n, m, s, d): # g : to store adjacency list # representation of graph. # e : to store list of even degree vertices # o : to store list of odd degree vertices g = [[] for i in range(n + 1)] e = [] o = [] deg = [0] * (n + 1) # Degrees of vertices vis = [0] * (n + 1) # To store visited in DFS odd = [0] * (n + 1) # Number of odd nodes # in components for i in range(m): g[s[i]].append(d[i]) g[d[i]].append(s[i]) deg[s[i]] += 1 deg[d[i]] += 1 # 'ans' is result and 'comp' # is component id ans = 0 comp = 0 for i in range(1, n + 1): if (vis[i] == 0): comp += 1 dfs(g, vis, odd, deg, comp, i) # Checking if connected component # is odd. if (odd[comp] == 0): e.append(comp) # Checking if connected component # is even. else: o.append(comp) # If whole graph is a single connected # component with even degree. if (len(o) == 0 and len(e) == 1): return 0 # If all connected component is even if (len(o) == 0): return len(e) # If graph have atleast one # even connected component if (len(e) != 0): ans += len(e) # For all the odd connected component. for i in range(len(o)): ans += odd[i] // 2 return ans # Driver Codeif __name__ == '__main__': n = 3 m = 2 source = [ 1, 2 ] destination = [ 2, 3] print(minEdge(n, m, source, destination)) # This code is contributed by PranchalK
1
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.
PranchalKatiyar
sanjeev2552
Euler-Circuit
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "Given a undirected graph of n nodes and m edges. The task is to find minimum edges required to make Euler Circuit in the given graph."
},
{
"code": null,
"e": 196,
"s": 186,
"text": "Examples:"
},
{
"code": null,
"e": 328,
"s": 196,
"text": "Input : n = 3, \n m = 2\n Edges[] = {{1, 2}, {2, 3}}\nOutput : 1\n\nBy connecting 1 to 3, we can create a Euler Circuit.\n\n"
},
{
"code": null,
"e": 508,
"s": 328,
"text": "For a Euler Circuit to exist in the graph we require that every node should have even degree because then there exists an edge that can be used to exit the node after entering it."
},
{
"code": null,
"e": 1248,
"s": 508,
"text": "Now, there can be two case:1. There is one connected component in the graphIn this case, if all the nodes in the graph is of even degree then we say that the graph already have a Euler Circuit and we don’t need to add any edge in it. But if there is any node with odd degree we need to add edges.There can be even number of odd degree vertices in the graph. This can be easily proved by the fact that the sum of degrees from the even degrees node and degrees from odd degrees node should match the total degrees that is always even as every edge contributes two to this sum. Now, if we pair up random odd degree nodes in the graph and add an edge between them we can make all nodes to have even degree and thus make an Euler Circuit exist."
},
{
"code": null,
"e": 2122,
"s": 1248,
"text": "2. There are disconnected components in the graphWe first mark component as odd and even. Odd components are those which have at least one odd degree node in them. Take all the even components and select a random vertex from every component and line them up linearly. Now we add an edge between adjacent vertices. So we have connected the even components and made an equivalent odd components that has two nodes with odd degree.Now to deal with odd components i.e components with at least one odd degree node. We can connect all these odd components using edges whose number is equal to the number of disconnected components. This can be done by placing the components in the cyclic order and picking two odd degree nodes from every component and using these to connect to the components on either side. Now we have a single connected component for which we have discussed."
},
{
"code": null,
"e": 2164,
"s": 2122,
"text": "Below is implementation of this approach:"
},
{
"code": null,
"e": 2168,
"s": 2164,
"text": "C++"
},
{
"code": null,
"e": 2173,
"s": 2168,
"text": "Java"
},
{
"code": null,
"e": 2181,
"s": 2173,
"text": "Python3"
},
{
"code": "// C++ program to find minimum edge required// to make Euler Circuit#include <bits/stdc++.h>using namespace std; // Depth-First Search to find a connected// componentvoid dfs(vector<int> g[], int vis[], int odd[], int deg[], int comp, int v){ vis[v] = 1; if (deg[v]%2 == 1) odd[comp]++; for (int u : g[v]) if (vis[u] == 0) dfs(g, vis, odd, deg, comp, u);} // Return minimum edge required to make Euler// Circuitint minEdge(int n, int m, int s[], int d[]){ // g : to store adjacency list // representation of graph. // e : to store list of even degree vertices // o : to store list of odd degree vertices vector<int> g[n+1], e, o; int deg[n+1]; // Degrees of vertices int vis[n+1]; // To store visited in DFS int odd[n+1]; // Number of odd nodes in components memset(deg, 0, sizeof(deg)); memset(vis, 0, sizeof(vis)); memset(odd, 0, sizeof(odd)); for (int i = 0; i < m; i++) { g[s[i]].push_back(d[i]); g[d[i]].push_back(s[i]); deg[s[i]]++; deg[d[i]]++; } // 'ans' is result and 'comp' is component id int ans = 0, comp = 0; for (int i = 1; i <= n; i++) { if (vis[i]==0) { comp++; dfs(g, vis, odd, deg, comp, i); // Checking if connected component // is odd. if (odd[comp] == 0) e.push_back(comp); // Checking if connected component // is even. else o.push_back(comp); } } // If whole graph is a single connected // component with even degree. if (o.size() == 0 && e.size() == 1) return 0; // If all connected component is even if (o.size() == 0) return e.size(); // If graph have atleast one even connected // component if (e.size() != 0) ans += e.size(); // For all the odd connected component. for (int i : o) ans += odd[i]/2; return ans;} // Driven Programint main(){ int n = 3, m = 2; int source[] = { 1, 2 }; int destination[] = { 2, 3 }; cout << minEdge(n, m, source, destination) << endl; return 0;}",
"e": 4377,
"s": 2181,
"text": null
},
{
"code": "// Java program to find minimum edge// required to make Euler Circuitimport java.io.*;import java.util.*; class GFG { // Depth-First Search to find // a connected component static void dfs(Vector<Integer>[] g, int[] vis, int[] odd, int[] deg, int comp, int v) { vis[v] = 1; if (deg[v] % 2 == 1) odd[comp]++; for (int u : g[v]) if (vis[u] == 0) dfs(g, vis, odd, deg, comp, u); } // Return minimum edge required // to make Euler Circuit static int minEdge(int n, int m, int[] s, int[] d) { // g : to store adjacency list // representation of graph. // e : to store list of even degree vertices // o : to store list of odd degree vertices @SuppressWarnings(\"unchecked\") Vector<Integer>[] g = new Vector[n + 1]; Vector<Integer> e = new Vector<>(); Vector<Integer> o = new Vector<>(); for (int i = 0; i < n + 1; i++) g[i] = new Vector<>(); // Degrees of vertices int[] deg = new int[n + 1]; // To store visited in DFS int[] vis = new int[n + 1]; // Number of odd nodes in components int[] odd = new int[n + 1]; Arrays.fill(deg, 0); Arrays.fill(vis, 0); Arrays.fill(odd, 0); for (int i = 0; i < m; i++) { g[s[i]].add(d[i]); g[d[i]].add(s[i]); deg[s[i]]++; deg[d[i]]++; } // 'ans' is result and // 'comp' is component id int ans = 0, comp = 0; for (int i = 1; i <= n; i++) { if (vis[i] == 0) { comp++; dfs(g, vis, odd, deg, comp, i); // Checking if connected component // is odd. if (odd[comp] == 0) e.add(comp); // Checking if connected component // is even. else o.add(comp); } } // If whole graph is a single connected // component with even degree. if (o.size() == 0 && e.size() == 1) return 0; // If all connected component is even if (o.size() == 0) return e.size(); // If graph have atleast one // even connected component if (e.size() != 0) ans += e.size(); // For all the odd connected component. for (int i : o) ans += odd[i] / 2; return ans; } // Driver Code public static void main(String[] args) throws IOException { int n = 3, m = 2; int[] source = { 1, 2 }; int[] destination = { 2, 3 }; System.out.println(minEdge(n, m, source, destination)); }} // This code is contributed by// sanjeev2552",
"e": 7354,
"s": 4377,
"text": null
},
{
"code": "# Python3 program to find minimum edge # required to make Euler Circuit # Depth-First Search to find a # connected component def dfs(g, vis, odd, deg, comp, v): vis[v] = 1 if (deg[v] % 2 == 1): odd[comp] += 1 for u in range(len(g[v])): if (vis[u] == 0): dfs(g, vis, odd, deg, comp, u) # Return minimum edge required to# make Euler Circuit def minEdge(n, m, s, d): # g : to store adjacency list # representation of graph. # e : to store list of even degree vertices # o : to store list of odd degree vertices g = [[] for i in range(n + 1)] e = [] o = [] deg = [0] * (n + 1) # Degrees of vertices vis = [0] * (n + 1) # To store visited in DFS odd = [0] * (n + 1) # Number of odd nodes # in components for i in range(m): g[s[i]].append(d[i]) g[d[i]].append(s[i]) deg[s[i]] += 1 deg[d[i]] += 1 # 'ans' is result and 'comp' # is component id ans = 0 comp = 0 for i in range(1, n + 1): if (vis[i] == 0): comp += 1 dfs(g, vis, odd, deg, comp, i) # Checking if connected component # is odd. if (odd[comp] == 0): e.append(comp) # Checking if connected component # is even. else: o.append(comp) # If whole graph is a single connected # component with even degree. if (len(o) == 0 and len(e) == 1): return 0 # If all connected component is even if (len(o) == 0): return len(e) # If graph have atleast one # even connected component if (len(e) != 0): ans += len(e) # For all the odd connected component. for i in range(len(o)): ans += odd[i] // 2 return ans # Driver Codeif __name__ == '__main__': n = 3 m = 2 source = [ 1, 2 ] destination = [ 2, 3] print(minEdge(n, m, source, destination)) # This code is contributed by PranchalK",
"e": 9392,
"s": 7354,
"text": null
},
{
"code": null,
"e": 9395,
"s": 9392,
"text": "1\n"
},
{
"code": null,
"e": 9691,
"s": 9395,
"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."
},
{
"code": null,
"e": 9816,
"s": 9691,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9832,
"s": 9816,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 9844,
"s": 9832,
"text": "sanjeev2552"
},
{
"code": null,
"e": 9858,
"s": 9844,
"text": "Euler-Circuit"
},
{
"code": null,
"e": 9864,
"s": 9858,
"text": "Graph"
},
{
"code": null,
"e": 9870,
"s": 9864,
"text": "Graph"
}
]
|
Find Nth root of M | Practice | GeeksforGeeks | You are given 2 numbers (n , m); the task is to find n√m (nth root of m).
Example 1:
Input: n = 2, m = 9
Output: 3
Explanation: 32 = 9
Example 2:
Input: n = 3, m = 9
Output: -1
Explanation: 3rd root of 9 is not
integer.
Your Task:
You don't need to read or print anyhting. Your task is to complete the function NthRoot() which takes n and m as input parameter and returns the nth root of m. If the root is not integer then returns -1.
Expected Time Complexity: O(n* log(m))
Expected Space Complexity: O(1)
Constraints:
1 <= n <= 30
1 <= m <= 109
+4
yoginpahuja_033 weeks ago
int l=1;
int h=m;
while(l<=h)
{
int mid=(l+h)/2;
if(pow(mid,n)==m)
return mid;
else if(pow(mid,n)>m)
h=mid-1;
else
l=mid+1;
}
return -1;
0
manishmawatwal1 month ago
def NthRoot(self, n, m): # Code here ans = pow(m, 1 / n) ans_floor = math.floor(ans) ans_ceil = math.ceil(ans) if math.pow(ans_floor, n) == m: return ans_floor elif math.pow(ans_ceil, n) == m: return ans_ceil else: return -1
0
shivshivamsahu1 month ago
int NthRoot(int n, int m){ // Code here. if(n == 1){ return m; } if(m == 1){ return 1; } int low = 1, high = sqrt(m); while(low <= high){ int mid = low + (high - low)/2; long long power = 1; for(int i = 1; i <= n; i++){ power *= mid; if(power > m*1LL){ break; } } if(power == m){ return mid; } if(power > m){ high = mid-1; } else{ low = mid+1; } } return -1;}
+2
dheepanbalajib2 months ago
int NthRoot(int n, int m){
long int a=0;
long int ele=0;
while(ele<=m){
ele=pow(a,n);
if(ele==m){
return a;
}
a++;
}
return -1;
}
#simple solution in c++;
+2
rohankundu8593 months ago
//C++ Solution
int NthRoot(int n, int m){ // Code here. int start=1; int end=m; while(start<=end) { int mid=(start+end)/2; if(pow(mid,n)==m) { return mid; } else if(pow(mid,n)>m) { end=mid-1; } else if(pow(mid,n)<m) { start=mid+1; } } return -1;}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 314,
"s": 238,
"text": "You are given 2 numbers (n , m); the task is to find n√m (nth root of m).\n "
},
{
"code": null,
"e": 325,
"s": 314,
"text": "Example 1:"
},
{
"code": null,
"e": 376,
"s": 325,
"text": "Input: n = 2, m = 9\nOutput: 3\nExplanation: 32 = 9\n"
},
{
"code": null,
"e": 387,
"s": 376,
"text": "Example 2:"
},
{
"code": null,
"e": 462,
"s": 387,
"text": "Input: n = 3, m = 9\nOutput: -1\nExplanation: 3rd root of 9 is not\ninteger.\n"
},
{
"code": null,
"e": 681,
"s": 464,
"text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function NthRoot() which takes n and m as input parameter and returns the nth root of m. If the root is not integer then returns -1.\n "
},
{
"code": null,
"e": 754,
"s": 681,
"text": "Expected Time Complexity: O(n* log(m))\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 794,
"s": 754,
"text": "Constraints:\n1 <= n <= 30\n1 <= m <= 109"
},
{
"code": null,
"e": 797,
"s": 794,
"text": "+4"
},
{
"code": null,
"e": 823,
"s": 797,
"text": "yoginpahuja_033 weeks ago"
},
{
"code": null,
"e": 1056,
"s": 823,
"text": " int l=1;\n\t int h=m;\n\t while(l<=h)\n\t {\n\t int mid=(l+h)/2;\n\t if(pow(mid,n)==m)\n\t return mid;\n\t else if(pow(mid,n)>m)\n\t h=mid-1;\n\t else\n\t l=mid+1;\n\t }\n\t return -1;"
},
{
"code": null,
"e": 1058,
"s": 1056,
"text": "0"
},
{
"code": null,
"e": 1084,
"s": 1058,
"text": "manishmawatwal1 month ago"
},
{
"code": null,
"e": 1370,
"s": 1084,
"text": " def NthRoot(self, n, m): # Code here ans = pow(m, 1 / n) ans_floor = math.floor(ans) ans_ceil = math.ceil(ans) if math.pow(ans_floor, n) == m: return ans_floor elif math.pow(ans_ceil, n) == m: return ans_ceil else: return -1"
},
{
"code": null,
"e": 1372,
"s": 1370,
"text": "0"
},
{
"code": null,
"e": 1398,
"s": 1372,
"text": "shivshivamsahu1 month ago"
},
{
"code": null,
"e": 1990,
"s": 1398,
"text": " int NthRoot(int n, int m){ // Code here. if(n == 1){ return m; } if(m == 1){ return 1; } int low = 1, high = sqrt(m); while(low <= high){ int mid = low + (high - low)/2; long long power = 1; for(int i = 1; i <= n; i++){ power *= mid; if(power > m*1LL){ break; } } if(power == m){ return mid; } if(power > m){ high = mid-1; } else{ low = mid+1; } } return -1;} "
},
{
"code": null,
"e": 1993,
"s": 1990,
"text": "+2"
},
{
"code": null,
"e": 2020,
"s": 1993,
"text": "dheepanbalajib2 months ago"
},
{
"code": null,
"e": 2262,
"s": 2020,
"text": "int NthRoot(int n, int m){\n\t long int a=0;\n\t long int ele=0;\n\t while(ele<=m){\n\t ele=pow(a,n);\n\t if(ele==m){\n\t return a;\n\t }\n\t a++;\n\t }\n\t return -1;\n } \n #simple solution in c++;"
},
{
"code": null,
"e": 2265,
"s": 2262,
"text": "+2"
},
{
"code": null,
"e": 2291,
"s": 2265,
"text": "rohankundu8593 months ago"
},
{
"code": null,
"e": 2306,
"s": 2291,
"text": "//C++ Solution"
},
{
"code": null,
"e": 2675,
"s": 2308,
"text": " int NthRoot(int n, int m){ // Code here. int start=1; int end=m; while(start<=end) { int mid=(start+end)/2; if(pow(mid,n)==m) { return mid; } else if(pow(mid,n)>m) { end=mid-1; } else if(pow(mid,n)<m) { start=mid+1; } } return -1;} "
},
{
"code": null,
"e": 2821,
"s": 2675,
"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": 2857,
"s": 2821,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2867,
"s": 2857,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2877,
"s": 2867,
"text": "\nContest\n"
},
{
"code": null,
"e": 2940,
"s": 2877,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3125,
"s": 2940,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3409,
"s": 3125,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 3555,
"s": 3409,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 3632,
"s": 3555,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 3673,
"s": 3632,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 3701,
"s": 3673,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 3772,
"s": 3701,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 3959,
"s": 3772,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
]
|
MoviePy Composite Video – Adding Cross Fade in Effect | 21 May, 2021
In this article we will see how we can add cross fade in effect in composite video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Meaning of composite is combining different elements, composite video is the combination of different video clips unlike stacking and concatenation of video files composite files are easy to implement but complex structure. Composite file combine the clips over one another and get played at same time, position and timing of video playback can be set any time. Cross fade is effect is set so that smooth transition occurs when clips get changed. Cross fade means to fade in (a sound or image) in a motion picture or a radio or television program while fading out another sound or image.
In order to do this we will use crossfadein method with the VideoFileClip objectSyntax : clip.crossfadein(n)Argument : It takes float as argumentReturn : It returns VideoFileClip object
Below is the implementation
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting only first 5 secondsclip1 = clip.subclip(0, 5) # rotating clip by 180 degree to get the clip3clip2 = clip1.rotate(180).set_start(4) # adding cross fade of 2 seconds in the clip2clip2 = clip2.crossfadein(2.0) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip from itclip1 = clip.subclip(0, 5) # mirroring image according to the y axisclip2 = clip.fx(vfx.mirror_y).set_start(4) # adding cross fade of 2 seconds in the clip2clip2 = clip2.crossfadein(2.0) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480)
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
MoviePy - Done.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
anikaseth98
Python-MoviePy
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
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 822,
"s": 28,
"text": "In this article we will see how we can add cross fade in effect in composite video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Meaning of composite is combining different elements, composite video is the combination of different video clips unlike stacking and concatenation of video files composite files are easy to implement but complex structure. Composite file combine the clips over one another and get played at same time, position and timing of video playback can be set any time. Cross fade is effect is set so that smooth transition occurs when clips get changed. Cross fade means to fade in (a sound or image) in a motion picture or a radio or television program while fading out another sound or image."
},
{
"code": null,
"e": 1010,
"s": 822,
"text": "In order to do this we will use crossfadein method with the VideoFileClip objectSyntax : clip.crossfadein(n)Argument : It takes float as argumentReturn : It returns VideoFileClip object "
},
{
"code": null,
"e": 1040,
"s": 1010,
"text": "Below is the implementation "
},
{
"code": null,
"e": 1048,
"s": 1040,
"text": "Python3"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.webm\") # getting only first 5 secondsclip1 = clip.subclip(0, 5) # rotating clip by 180 degree to get the clip3clip2 = clip1.rotate(180).set_start(4) # adding cross fade of 2 seconds in the clip2clip2 = clip2.crossfadein(2.0) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480)",
"e": 1545,
"s": 1048,
"text": null
},
{
"code": null,
"e": 1555,
"s": 1545,
"text": "Output : "
},
{
"code": null,
"e": 1806,
"s": 1555,
"text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n "
},
{
"code": null,
"e": 1823,
"s": 1806,
"text": "Another example "
},
{
"code": null,
"e": 1831,
"s": 1823,
"text": "Python3"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip from itclip1 = clip.subclip(0, 5) # mirroring image according to the y axisclip2 = clip.fx(vfx.mirror_y).set_start(4) # adding cross fade of 2 seconds in the clip2clip2 = clip2.crossfadein(2.0) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480)",
"e": 2299,
"s": 1831,
"text": null
},
{
"code": null,
"e": 2309,
"s": 2299,
"text": "Output : "
},
{
"code": null,
"e": 2750,
"s": 2309,
"text": "Moviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4"
},
{
"code": null,
"e": 2764,
"s": 2752,
"text": "anikaseth98"
},
{
"code": null,
"e": 2779,
"s": 2764,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 2786,
"s": 2779,
"text": "Python"
},
{
"code": null,
"e": 2884,
"s": 2786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2902,
"s": 2884,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2944,
"s": 2902,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2979,
"s": 2944,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3011,
"s": 2979,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3037,
"s": 3011,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3066,
"s": 3037,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3093,
"s": 3066,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3114,
"s": 3093,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3137,
"s": 3114,
"text": "Introduction To PYTHON"
}
]
|
Python | Plotting bar charts in excel sheet using XlsxWriter module | 19 May, 2021
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Bar, Stacked Bar, Percent Stacked Bar chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Bar Chart.For plotting the simple Bar chart on an excel sheet, use add_chart() method with type ‘bar’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a bar chart object .chart1 = workbook.add_chart({'type': 'bar'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()
Output:
Code #2 : Plot the Stacked Bar Chart.For plotting the Stacked Bar chart on an excel sheet, use add_chart() method with type ‘bar’ and subtype ‘stacked’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a stacked bar chart object .chart1 = workbook.add_chart({'type': 'bar', 'subtype': 'stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()
Output:
Code #3 : Plot the Percent Stacked bar Chart.For plotting the Percent Stacked Bar chart on an excel sheet, use add_chart() method with type ‘bar’ and subtype ‘percent_stacked’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a percent stacked bar chart object .chart1 = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()
Output:
anikaseth98
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 865,
"s": 28,
"text": "Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Bar, Stacked Bar, Percent Stacked Bar chart etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Bar Chart.For plotting the simple Bar chart on an excel sheet, use add_chart() method with type ‘bar’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 873,
"s": 865,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a bar chart object .chart1 = workbook.add_chart({'type': 'bar'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()",
"e": 2955,
"s": 873,
"text": null
},
{
"code": null,
"e": 2965,
"s": 2955,
"text": "Output: "
},
{
"code": null,
"e": 3160,
"s": 2965,
"text": " Code #2 : Plot the Stacked Bar Chart.For plotting the Stacked Bar chart on an excel sheet, use add_chart() method with type ‘bar’ and subtype ‘stacked’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 3168,
"s": 3160,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a stacked bar chart object .chart1 = workbook.add_chart({'type': 'bar', 'subtype': 'stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()",
"e": 5281,
"s": 3168,
"text": null
},
{
"code": null,
"e": 5291,
"s": 5281,
"text": "Output: "
},
{
"code": null,
"e": 5510,
"s": 5291,
"text": " Code #3 : Plot the Percent Stacked bar Chart.For plotting the Percent Stacked Bar chart on an excel sheet, use add_chart() method with type ‘bar’ and subtype ‘percent_stacked’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 5518,
"s": 5510,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_bar3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method.worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a percent stacked bar chart object .chart1 = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart titlechart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet# the top-left corner of a chart# is anchored to cell E2 .worksheet.insert_chart('E2', chart1) # Finally, close the Excel file# via the close() method.workbook.close()",
"e": 7647,
"s": 5518,
"text": null
},
{
"code": null,
"e": 7655,
"s": 7647,
"text": "Output:"
},
{
"code": null,
"e": 7669,
"s": 7657,
"text": "anikaseth98"
},
{
"code": null,
"e": 7684,
"s": 7669,
"text": "python-modules"
},
{
"code": null,
"e": 7691,
"s": 7684,
"text": "Python"
},
{
"code": null,
"e": 7789,
"s": 7691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7807,
"s": 7789,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7829,
"s": 7807,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7871,
"s": 7829,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7903,
"s": 7871,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7929,
"s": 7903,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7950,
"s": 7929,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 7977,
"s": 7950,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8006,
"s": 7977,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 8029,
"s": 8006,
"text": "Introduction To PYTHON"
}
]
|
How to resolve unhandled exceptions in Node.js ? | 20 May, 2020
There are two approaches to resolve unhandled exceptions in Node.js that are discussed below:
Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.
Example:
try { // The synchronous code that // we want to catch thrown // errors on var err = new Error('Hello') throw err} catch (err) { // Handle the error safely console.log(err)}
Note: However, be careful not to use try-catch in asynchronous code, as an asynchronously thrown error will not be caught.
try { setTimeout(function() { var err = new Error('Hello') throw err }, 1000)}catch (err) { // Example error won't be caught // here... crashing our application // hence the need for domains}
Approach 2: Using Process: A good practice says, you should use Process to handle exception. A process is a global object that provides information about the current Node.js process. The process is a listener function that is always listening to the events.Few events are:
Disconnect
Exit
Message
Multiple Resolves
Unhandled Exception
Rejection Handled
Uncaught Exception
Warning
The most effective and efficient approach is to use Process. If any uncaught or unhandled exception occurs in your code flow, that exception will be caught in code shown below:
Example:
process.on('uncaughtException', function(err) { // Handle the error safely console.log(err)})
The above code will be able to handle any sort of unhandled exception which occurs in Node.js.
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 122,
"s": 28,
"text": "There are two approaches to resolve unhandled exceptions in Node.js that are discussed below:"
},
{
"code": null,
"e": 402,
"s": 122,
"text": "Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block."
},
{
"code": null,
"e": 411,
"s": 402,
"text": "Example:"
},
{
"code": "try { // The synchronous code that // we want to catch thrown // errors on var err = new Error('Hello') throw err} catch (err) { // Handle the error safely console.log(err)}",
"e": 618,
"s": 411,
"text": null
},
{
"code": null,
"e": 741,
"s": 618,
"text": "Note: However, be careful not to use try-catch in asynchronous code, as an asynchronously thrown error will not be caught."
},
{
"code": "try { setTimeout(function() { var err = new Error('Hello') throw err }, 1000)}catch (err) { // Example error won't be caught // here... crashing our application // hence the need for domains}",
"e": 968,
"s": 741,
"text": null
},
{
"code": null,
"e": 1241,
"s": 968,
"text": "Approach 2: Using Process: A good practice says, you should use Process to handle exception. A process is a global object that provides information about the current Node.js process. The process is a listener function that is always listening to the events.Few events are:"
},
{
"code": null,
"e": 1252,
"s": 1241,
"text": "Disconnect"
},
{
"code": null,
"e": 1257,
"s": 1252,
"text": "Exit"
},
{
"code": null,
"e": 1265,
"s": 1257,
"text": "Message"
},
{
"code": null,
"e": 1283,
"s": 1265,
"text": "Multiple Resolves"
},
{
"code": null,
"e": 1303,
"s": 1283,
"text": "Unhandled Exception"
},
{
"code": null,
"e": 1321,
"s": 1303,
"text": "Rejection Handled"
},
{
"code": null,
"e": 1340,
"s": 1321,
"text": "Uncaught Exception"
},
{
"code": null,
"e": 1348,
"s": 1340,
"text": "Warning"
},
{
"code": null,
"e": 1525,
"s": 1348,
"text": "The most effective and efficient approach is to use Process. If any uncaught or unhandled exception occurs in your code flow, that exception will be caught in code shown below:"
},
{
"code": null,
"e": 1534,
"s": 1525,
"text": "Example:"
},
{
"code": "process.on('uncaughtException', function(err) { // Handle the error safely console.log(err)})",
"e": 1636,
"s": 1534,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1636,
"text": "The above code will be able to handle any sort of unhandled exception which occurs in Node.js."
},
{
"code": null,
"e": 1744,
"s": 1731,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 1751,
"s": 1744,
"text": "Picked"
},
{
"code": null,
"e": 1759,
"s": 1751,
"text": "Node.js"
},
{
"code": null,
"e": 1776,
"s": 1759,
"text": "Web Technologies"
},
{
"code": null,
"e": 1803,
"s": 1776,
"text": "Web technologies Questions"
}
]
|
Text Generation using Recurrent Long Short Term Memory Network | 25 Jun, 2021
This article will demonstrate how to build a Text Generator by building a Recurrent Long Short Term Memory Network. The conceptual procedure of training the network is to first feed the network a mapping of each character present in the text on which the network is training to a unique number. Each character is then hot-encoded into a vector which is the required format for the network. The data for the described procedure was downloaded from Kaggle. This dataset contains the articles published in the New York Times from April 2017 to April 2018. separated according to the month of publication. The dataset is in the form of .csv file which contains the url of the published article along with other details. Any one random url was chosen for the training process and then on visiting this url, the text was copied into a text file and this text file was used for the training process.Step 1: Importing the required libraries
Python3
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as npimport tensorflow as tf from keras.models import Sequentialfrom keras.layers import Dense, Activationfrom keras.layers import LSTM from keras.optimizers import RMSprop from keras.callbacks import LambdaCallbackfrom keras.callbacks import ModelCheckpointfrom keras.callbacks import ReduceLROnPlateauimport randomimport sys
Step 2: Loading the data into a string
Python3
# Changing the working location to the location of the text filecd C:\Users\Dev\Desktop\Kaggle\New York Times # Reading the text file into a stringwith open('article1.txt', 'r') as file: text = file.read() # A preview of the text file print(text)
Step 3: Creating a mapping from each unique character in the text to a unique number
Python3
# Storing all the unique characters present in the textvocabulary = sorted(list(set(text))) # Creating dictionaries to map each character to an indexchar_to_indices = dict((c, i) for i, c in enumerate(vocabulary))indices_to_char = dict((i, c) for i, c in enumerate(vocabulary)) print(vocabulary)
Step 4: Pre-processing the data
Python3
# Dividing the text into subsequences of length max_length# So that at each time step the next max_length characters# are fed into the networkmax_length = 100steps = 5sentences = []next_chars = []for i in range(0, len(text) - max_length, steps): sentences.append(text[i: i + max_length]) next_chars.append(text[i + max_length]) # Hot encoding each character into a boolean vectorX = np.zeros((len(sentences), max_length, len(vocabulary)), dtype = np.bool)y = np.zeros((len(sentences), len(vocabulary)), dtype = np.bool)for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_to_indices[char]] = 1 y[i, char_to_indices[next_chars[i]]] = 1
Step 5: Building the LSTM network
Python3
# Building the LSTM network for the taskmodel = Sequential()model.add(LSTM(128, input_shape =(max_length, len(vocabulary))))model.add(Dense(len(vocabulary)))model.add(Activation('softmax'))optimizer = RMSprop(lr = 0.01)model.compile(loss ='categorical_crossentropy', optimizer = optimizer)
Step 6: Defining some helper functions which will be used during the training of the networkNote that the first two functions given below have been referred from the documentation of the official text generation example from the Keras team.a) Helper function to sample the next character:
Python3
# Helper function to sample an index from a probability arraydef sample_index(preds, temperature = 1.0): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas)
b) Helper function to generate text after each epoch
Python3
# Helper function to generate text after the end of each epochdef on_epoch_end(epoch, logs): print() print('----- Generating text after Epoch: % d' % epoch) start_index = random.randint(0, len(text) - max_length - 1) for diversity in [0.2, 0.5, 1.0, 1.2]: print('----- diversity:', diversity) generated = '' sentence = text[start_index: start_index + max_length] generated += sentence print('----- Generating with seed: "' + sentence + '"') sys.stdout.write(generated) for i in range(400): x_pred = np.zeros((1, max_length, len(vocabulary))) for t, char in enumerate(sentence): x_pred[0, t, char_to_indices[char]] = 1. preds = model.predict(x_pred, verbose = 0)[0] next_index = sample_index(preds, diversity) next_char = indices_to_char[next_index] generated += next_char sentence = sentence[1:] + next_char sys.stdout.write(next_char) sys.stdout.flush() print()print_callback = LambdaCallback(on_epoch_end = on_epoch_end)
c) Helper function to save the model after each epoch in which loss decreases
Python3
# Defining a helper function to save the model after each epoch# in which the loss decreasesfilepath = "weights.hdf5"checkpoint = ModelCheckpoint(filepath, monitor ='loss', verbose = 1, save_best_only = True, mode ='min')
d) Helper function to reduce the learning rate each time the learning plateaus
Python3
# Defining a helper function to reduce the learning rate each time# the learning plateausreduce_alpha = ReduceLROnPlateau(monitor ='loss', factor = 0.2, patience = 1, min_lr = 0.001)callbacks = [print_callback, checkpoint, reduce_alpha]
Step 7: Training the LSTM model
Python3
# Training the LSTM modelmodel.fit(X, y, batch_size = 128, epochs = 500, callbacks = callbacks)
Step 8: Generating new and random text
Python3
# Defining a utility function to generate new and random text based on the# network's learningsdef generate_text(length, diversity): # Get random starting text start_index = random.randint(0, len(text) - max_length - 1) generated = '' sentence = text[start_index: start_index + max_length] generated += sentence for i in range(length): x_pred = np.zeros((1, max_length, len(vocabulary))) for t, char in enumerate(sentence): x_pred[0, t, char_to_indices[char]] = 1. preds = model.predict(x_pred, verbose = 0)[0] next_index = sample_index(preds, diversity) next_char = indices_to_char[next_index] generated += next_char sentence = sentence[1:] + next_char return generated print(generate_text(500, 0.2))
as5853535
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Getting started with Machine Learning
ML | Underfitting and Overfitting
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": 54,
"s": 26,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 988,
"s": 54,
"text": "This article will demonstrate how to build a Text Generator by building a Recurrent Long Short Term Memory Network. The conceptual procedure of training the network is to first feed the network a mapping of each character present in the text on which the network is training to a unique number. Each character is then hot-encoded into a vector which is the required format for the network. The data for the described procedure was downloaded from Kaggle. This dataset contains the articles published in the New York Times from April 2017 to April 2018. separated according to the month of publication. The dataset is in the form of .csv file which contains the url of the published article along with other details. Any one random url was chosen for the training process and then on visiting this url, the text was copied into a text file and this text file was used for the training process.Step 1: Importing the required libraries "
},
{
"code": null,
"e": 996,
"s": 988,
"text": "Python3"
},
{
"code": "from __future__ import absolute_import, division, print_function, unicode_literals import numpy as npimport tensorflow as tf from keras.models import Sequentialfrom keras.layers import Dense, Activationfrom keras.layers import LSTM from keras.optimizers import RMSprop from keras.callbacks import LambdaCallbackfrom keras.callbacks import ModelCheckpointfrom keras.callbacks import ReduceLROnPlateauimport randomimport sys",
"e": 1441,
"s": 996,
"text": null
},
{
"code": null,
"e": 1481,
"s": 1441,
"text": "Step 2: Loading the data into a string "
},
{
"code": null,
"e": 1489,
"s": 1481,
"text": "Python3"
},
{
"code": "# Changing the working location to the location of the text filecd C:\\Users\\Dev\\Desktop\\Kaggle\\New York Times # Reading the text file into a stringwith open('article1.txt', 'r') as file: text = file.read() # A preview of the text file print(text)",
"e": 1741,
"s": 1489,
"text": null
},
{
"code": null,
"e": 1827,
"s": 1741,
"text": "Step 3: Creating a mapping from each unique character in the text to a unique number "
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "Python3"
},
{
"code": "# Storing all the unique characters present in the textvocabulary = sorted(list(set(text))) # Creating dictionaries to map each character to an indexchar_to_indices = dict((c, i) for i, c in enumerate(vocabulary))indices_to_char = dict((i, c) for i, c in enumerate(vocabulary)) print(vocabulary)",
"e": 2131,
"s": 1835,
"text": null
},
{
"code": null,
"e": 2164,
"s": 2131,
"text": "Step 4: Pre-processing the data "
},
{
"code": null,
"e": 2172,
"s": 2164,
"text": "Python3"
},
{
"code": "# Dividing the text into subsequences of length max_length# So that at each time step the next max_length characters# are fed into the networkmax_length = 100steps = 5sentences = []next_chars = []for i in range(0, len(text) - max_length, steps): sentences.append(text[i: i + max_length]) next_chars.append(text[i + max_length]) # Hot encoding each character into a boolean vectorX = np.zeros((len(sentences), max_length, len(vocabulary)), dtype = np.bool)y = np.zeros((len(sentences), len(vocabulary)), dtype = np.bool)for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_to_indices[char]] = 1 y[i, char_to_indices[next_chars[i]]] = 1",
"e": 2867,
"s": 2172,
"text": null
},
{
"code": null,
"e": 2902,
"s": 2867,
"text": "Step 5: Building the LSTM network "
},
{
"code": null,
"e": 2910,
"s": 2902,
"text": "Python3"
},
{
"code": "# Building the LSTM network for the taskmodel = Sequential()model.add(LSTM(128, input_shape =(max_length, len(vocabulary))))model.add(Dense(len(vocabulary)))model.add(Activation('softmax'))optimizer = RMSprop(lr = 0.01)model.compile(loss ='categorical_crossentropy', optimizer = optimizer)",
"e": 3200,
"s": 2910,
"text": null
},
{
"code": null,
"e": 3491,
"s": 3200,
"text": "Step 6: Defining some helper functions which will be used during the training of the networkNote that the first two functions given below have been referred from the documentation of the official text generation example from the Keras team.a) Helper function to sample the next character: "
},
{
"code": null,
"e": 3499,
"s": 3491,
"text": "Python3"
},
{
"code": "# Helper function to sample an index from a probability arraydef sample_index(preds, temperature = 1.0): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas)",
"e": 3835,
"s": 3499,
"text": null
},
{
"code": null,
"e": 3889,
"s": 3835,
"text": "b) Helper function to generate text after each epoch "
},
{
"code": null,
"e": 3897,
"s": 3889,
"text": "Python3"
},
{
"code": "# Helper function to generate text after the end of each epochdef on_epoch_end(epoch, logs): print() print('----- Generating text after Epoch: % d' % epoch) start_index = random.randint(0, len(text) - max_length - 1) for diversity in [0.2, 0.5, 1.0, 1.2]: print('----- diversity:', diversity) generated = '' sentence = text[start_index: start_index + max_length] generated += sentence print('----- Generating with seed: \"' + sentence + '\"') sys.stdout.write(generated) for i in range(400): x_pred = np.zeros((1, max_length, len(vocabulary))) for t, char in enumerate(sentence): x_pred[0, t, char_to_indices[char]] = 1. preds = model.predict(x_pred, verbose = 0)[0] next_index = sample_index(preds, diversity) next_char = indices_to_char[next_index] generated += next_char sentence = sentence[1:] + next_char sys.stdout.write(next_char) sys.stdout.flush() print()print_callback = LambdaCallback(on_epoch_end = on_epoch_end)",
"e": 5008,
"s": 3897,
"text": null
},
{
"code": null,
"e": 5087,
"s": 5008,
"text": "c) Helper function to save the model after each epoch in which loss decreases "
},
{
"code": null,
"e": 5095,
"s": 5087,
"text": "Python3"
},
{
"code": "# Defining a helper function to save the model after each epoch# in which the loss decreasesfilepath = \"weights.hdf5\"checkpoint = ModelCheckpoint(filepath, monitor ='loss', verbose = 1, save_best_only = True, mode ='min')",
"e": 5373,
"s": 5095,
"text": null
},
{
"code": null,
"e": 5453,
"s": 5373,
"text": "d) Helper function to reduce the learning rate each time the learning plateaus "
},
{
"code": null,
"e": 5461,
"s": 5453,
"text": "Python3"
},
{
"code": "# Defining a helper function to reduce the learning rate each time# the learning plateausreduce_alpha = ReduceLROnPlateau(monitor ='loss', factor = 0.2, patience = 1, min_lr = 0.001)callbacks = [print_callback, checkpoint, reduce_alpha]",
"e": 5727,
"s": 5461,
"text": null
},
{
"code": null,
"e": 5760,
"s": 5727,
"text": "Step 7: Training the LSTM model "
},
{
"code": null,
"e": 5768,
"s": 5760,
"text": "Python3"
},
{
"code": "# Training the LSTM modelmodel.fit(X, y, batch_size = 128, epochs = 500, callbacks = callbacks)",
"e": 5864,
"s": 5768,
"text": null
},
{
"code": null,
"e": 5904,
"s": 5864,
"text": "Step 8: Generating new and random text "
},
{
"code": null,
"e": 5912,
"s": 5904,
"text": "Python3"
},
{
"code": "# Defining a utility function to generate new and random text based on the# network's learningsdef generate_text(length, diversity): # Get random starting text start_index = random.randint(0, len(text) - max_length - 1) generated = '' sentence = text[start_index: start_index + max_length] generated += sentence for i in range(length): x_pred = np.zeros((1, max_length, len(vocabulary))) for t, char in enumerate(sentence): x_pred[0, t, char_to_indices[char]] = 1. preds = model.predict(x_pred, verbose = 0)[0] next_index = sample_index(preds, diversity) next_char = indices_to_char[next_index] generated += next_char sentence = sentence[1:] + next_char return generated print(generate_text(500, 0.2))",
"e": 6729,
"s": 5912,
"text": null
},
{
"code": null,
"e": 6739,
"s": 6729,
"text": "as5853535"
},
{
"code": null,
"e": 6754,
"s": 6739,
"text": "Neural Network"
},
{
"code": null,
"e": 6771,
"s": 6754,
"text": "Machine Learning"
},
{
"code": null,
"e": 6778,
"s": 6771,
"text": "Python"
},
{
"code": null,
"e": 6795,
"s": 6778,
"text": "Machine Learning"
},
{
"code": null,
"e": 6893,
"s": 6795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6916,
"s": 6893,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 6952,
"s": 6916,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6976,
"s": 6952,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 7014,
"s": 6976,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 7048,
"s": 7014,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 7076,
"s": 7048,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 7126,
"s": 7076,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7148,
"s": 7126,
"text": "Python map() function"
}
]
|
GATE | GATE CS 2010 | Question 33 | 19 Nov, 2018
A 5-stage pipelined processor has Instruction Fetch(IF),Instruction Decode(ID),Operand Fetch(OF),Perform Operation(PO)and Write Operand(WO)stages.The IF,ID,OF and WO stages take 1 clock cycle each for any instruction.The PO stage takes 1 clock cycle for ADD and SUB instructions,3 clock cycles for MUL instruction,and 6 clock cycles for DIV instruction respectively.Operand forwarding is used in the pipeline.What is the number of clock cycles needed to execute the following sequence of instructions?
Instruction Meaning of instruction
I0 :MUL R2 ,R0 ,R1 R2 ¬ R0 *R1
I1 :DIV R5 ,R3 ,R4 R5 ¬ R3/R4
I2 :ADD R2 ,R5 ,R2 R2 ¬ R5+R2
I3 :SUB R5 ,R2 ,R6 R5 ¬ R2-R6
(A) 13(B) 15(C) 17(D) 19Answer: (B)Explanation: Operand Forwarding : In this technique the value of operand is given to the concerned stage of dependent instruction before it is stored.
In the above question, I2 is dependent on I0 and I1, and I3 is dependent on I2.
Let’s see this question with a time-space diagram.
The above is a space-time diagram representing the pipeline in which the instructions gets executed.
Instruction 0 is a MUL operation which take 3 clock cycles of CPU in the PO stage, and at any other stage it takes only 1 cycle.
Instruction 1 is a DIV operation which take 6 clock cycles of CPU in the PO stage, and at any other stage it takes only 1 cycle.
It can be noticed here that even when the OF stage was free in the 4th clock cycle, then also the instruction 1 was not given to it. This is a design issue. The operands should be fetched only if they are going to get operated or executed in the next cycle, else there is a possibility of data corruption. As PO stage was not free in the next cycle hence OF was delayed and was done for instruction 1 only just before 1 cycle of going to PO stage.
Instruction 2 is an ADD operation which take 1 clock cycles of CPU in all stages. But it is a dependent operation. it needs the operands which are provided by Instruction 0 and 1.
Instruction 2 needs R5 and R2 to add, it gets R2 on time, because till the time Instruction 2 reaches its PO stage R2 would have been stored in memory. Now R5 is also needed, but Instruction 2’s PO and Instruction 1’s WO are in parallel. That means Instruction 2 can’t take the value of R5 before it is stored by Instruction 1. So here comes the concept of Operand Forwarding. Before Instruction 1 store it’s result/value which is R5, it can first forward it to instruction 2’s Fetch-Execute Buffer, so that Instruction 2 can also use it in parallel to Instruction’s WO stage. This will save extra clock cycles required( if Operand forwarding is not used, and R5 need to be taken from memory).
In Instruction 3, same operand forwarding concept is applied for the value of R2 which is computed by Instruction 2.
Hence operand forwarding saved 2 extra clock cycles here. ( 1 cycle in Instruction 2 and 1 cycle in Instruction 3).
So the total no of cycles are 15, which can be seen from the diagram, each instance of the stage represents 1 clock cycle. So total 15.Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 556,
"s": 54,
"text": "A 5-stage pipelined processor has Instruction Fetch(IF),Instruction Decode(ID),Operand Fetch(OF),Perform Operation(PO)and Write Operand(WO)stages.The IF,ID,OF and WO stages take 1 clock cycle each for any instruction.The PO stage takes 1 clock cycle for ADD and SUB instructions,3 clock cycles for MUL instruction,and 6 clock cycles for DIV instruction respectively.Operand forwarding is used in the pipeline.What is the number of clock cycles needed to execute the following sequence of instructions?"
},
{
"code": null,
"e": 773,
"s": 556,
"text": " Instruction Meaning of instruction\n I0 :MUL R2 ,R0 ,R1 R2 ¬ R0 *R1\n I1 :DIV R5 ,R3 ,R4 R5 ¬ R3/R4\n I2 :ADD R2 ,R5 ,R2 R2 ¬ R5+R2\n I3 :SUB R5 ,R2 ,R6 R5 ¬ R2-R6"
},
{
"code": null,
"e": 959,
"s": 773,
"text": "(A) 13(B) 15(C) 17(D) 19Answer: (B)Explanation: Operand Forwarding : In this technique the value of operand is given to the concerned stage of dependent instruction before it is stored."
},
{
"code": null,
"e": 1039,
"s": 959,
"text": "In the above question, I2 is dependent on I0 and I1, and I3 is dependent on I2."
},
{
"code": null,
"e": 1090,
"s": 1039,
"text": "Let’s see this question with a time-space diagram."
},
{
"code": null,
"e": 1191,
"s": 1090,
"text": "The above is a space-time diagram representing the pipeline in which the instructions gets executed."
},
{
"code": null,
"e": 1320,
"s": 1191,
"text": "Instruction 0 is a MUL operation which take 3 clock cycles of CPU in the PO stage, and at any other stage it takes only 1 cycle."
},
{
"code": null,
"e": 1449,
"s": 1320,
"text": "Instruction 1 is a DIV operation which take 6 clock cycles of CPU in the PO stage, and at any other stage it takes only 1 cycle."
},
{
"code": null,
"e": 1897,
"s": 1449,
"text": "It can be noticed here that even when the OF stage was free in the 4th clock cycle, then also the instruction 1 was not given to it. This is a design issue. The operands should be fetched only if they are going to get operated or executed in the next cycle, else there is a possibility of data corruption. As PO stage was not free in the next cycle hence OF was delayed and was done for instruction 1 only just before 1 cycle of going to PO stage."
},
{
"code": null,
"e": 2077,
"s": 1897,
"text": "Instruction 2 is an ADD operation which take 1 clock cycles of CPU in all stages. But it is a dependent operation. it needs the operands which are provided by Instruction 0 and 1."
},
{
"code": null,
"e": 2771,
"s": 2077,
"text": "Instruction 2 needs R5 and R2 to add, it gets R2 on time, because till the time Instruction 2 reaches its PO stage R2 would have been stored in memory. Now R5 is also needed, but Instruction 2’s PO and Instruction 1’s WO are in parallel. That means Instruction 2 can’t take the value of R5 before it is stored by Instruction 1. So here comes the concept of Operand Forwarding. Before Instruction 1 store it’s result/value which is R5, it can first forward it to instruction 2’s Fetch-Execute Buffer, so that Instruction 2 can also use it in parallel to Instruction’s WO stage. This will save extra clock cycles required( if Operand forwarding is not used, and R5 need to be taken from memory)."
},
{
"code": null,
"e": 2888,
"s": 2771,
"text": "In Instruction 3, same operand forwarding concept is applied for the value of R2 which is computed by Instruction 2."
},
{
"code": null,
"e": 3004,
"s": 2888,
"text": "Hence operand forwarding saved 2 extra clock cycles here. ( 1 cycle in Instruction 2 and 1 cycle in Instruction 3)."
},
{
"code": null,
"e": 3161,
"s": 3004,
"text": "So the total no of cycles are 15, which can be seen from the diagram, each instance of the stage represents 1 clock cycle. So total 15.Quiz of this Question"
},
{
"code": null,
"e": 3174,
"s": 3161,
"text": "GATE-CS-2010"
},
{
"code": null,
"e": 3192,
"s": 3174,
"text": "GATE-GATE CS 2010"
},
{
"code": null,
"e": 3197,
"s": 3192,
"text": "GATE"
}
]
|
8085 program to exchange content of HL register pair with DE register pair | In this program we will see how to exchange the content of DE and HL pair.
Write 8085 Assembly language program to swap the content of HL and DE register pair.
This process is very simple, 8085 has XCHG instruction. This instruction swaps DE and HL pair content. We are storing some values to DE and HL pair directly, and then exchange them using XCHG.
DE = 5678H
HL = CDEFH
DE = CDEFH
HL = 5678H | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "In this program we will see how to exchange the content of DE and HL pair."
},
{
"code": null,
"e": 1222,
"s": 1137,
"text": "Write 8085 Assembly language program to swap the content of HL and DE register pair."
},
{
"code": null,
"e": 1415,
"s": 1222,
"text": "This process is very simple, 8085 has XCHG instruction. This instruction swaps DE and HL pair content. We are storing some values to DE and HL pair directly, and then exchange them using XCHG."
},
{
"code": null,
"e": 1437,
"s": 1415,
"text": "DE = 5678H\nHL = CDEFH"
},
{
"code": null,
"e": 1459,
"s": 1437,
"text": "DE = CDEFH\nHL = 5678H"
}
]
|
C# | Types of Variables - GeeksforGeeks | 11 Jun, 2021
A variable is a name given to a memory location and all the operations done on the variable effects that memory location. In C#, all the variables must be declared before they can be used. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution.
Local variables
Instance variables or Non – Static Variables
Static Variables or Class Variables
Constant Variables
Readonly Variables
A variable defined within a block or method or constructor is called local variable.
These variables are created when the block is entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variables only within that block.
Example 1:
C#
// C# program to demonstrate// the local variablesusing System;class StudentDetails { // Method public void StudentAge() { // local variable age int age = 0; age = age + 10; Console.WriteLine("Student age is : " + age); } // Main Method public static void Main(String[] args) { // Creating object StudentDetails obj = new StudentDetails(); // calling the function obj.StudentAge(); }}
Output:
Student age is : 10
Explanation :In the above program, the variable “age” is a local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error as shown in below program.
Example 2:
C#
// C# program to demonstrate the error// due to using the local variable// outside its scopeusing System; class StudentDetails { // Method public void StudentAge() { // local variable age int age = 0; age = age + 10; } // Main Method public static void Main(String[] args) { // using local variable age outside it's scope Console.WriteLine("Student age is : " + age); }}
Error:
prog.cs(22,43): error CS0103: The name `age’ does not exist in the current context
Instance variables are non-static variables and are declared in a class but outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables.
Example:
C#
// C# program to illustrate the// Instance variablesusing System; class Marks { // These variables are instance variables. // These variables are in a class and // are not inside any function int engMarks; int mathsMarks; int phyMarks; // Main Method public static void Main(String[] args) { // first object Marks obj1 = new Marks(); obj1.engMarks = 90; obj1.mathsMarks = 80; obj1.phyMarks = 93; // second object Marks obj2 = new Marks(); obj2.engMarks = 95; obj2.mathsMarks = 70; obj2.phyMarks = 90; // displaying marks for first object Console.WriteLine("Marks for first object:"); Console.WriteLine(obj1.engMarks); Console.WriteLine(obj1.mathsMarks); Console.WriteLine(obj1.phyMarks); // displaying marks for second object Console.WriteLine("Marks for second object:"); Console.WriteLine(obj2.engMarks); Console.WriteLine(obj2.mathsMarks); Console.WriteLine(obj2.phyMarks); }}
Output :
Marks for first object:
90
80
93
Marks for second object:
95
70
90
Explanation: In the above program the variables, engMarks, mathsMarks, phyMarksare instance variables. If there are multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of the instance variable.
Static variables are also known as Class variables. If a variable is explicitly declared with the static modifier or if a variable is declared under any static block then these variables are known as static variables.
These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed automatically when execution ends.
Note: To access static variables, there is no need to create any object of that class, simply access the variable as:
class_name.variable_name;
Example:
C#
// C# program to illustrate// the static variablesusing System;class Emp { // static variable salary static double salary; static String name = "Aks"; // Main Method public static void Main(String[] args) { // accessing static variable // without object Emp.salary = 100000; Console.WriteLine(Emp.name + "'s average salary:" + Emp.salary); }}
Output:
Aks's average salary:100000
Note: Initialization of non-static variables is associated with instance creation and constructor calls, so non-static variables can be initialized through the constructor also. We don’t initialize a static variable through constructor because every time constructor call, it will override the existing value with a new value.
Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all object of a class.
We can access instance variables through object references and Static Variables can be accessed directly using class name.
In the life cycle of a class a static variable ie initialized one and only one time, whereas instance variables are initialized for 0 times if no instance is created and n times if n instances are created.
The Syntax for static and instance variables are :
class Example
{
static int a; // static variable
int b; // instance variable
}
If a variable is declared by using the keyword “const” then it as a constant variable and these constant variables can’t be modified once after their declaration, so it’s must initialize at the time of declaration only.
Example 1: Below program will show the error because no value is provided at the time of constant variable declaration.
C#
// C# program to illustrate the// constant variablesusing System;class Program { // constant variable max // but no value is provided const float max; // Main Method public static void Main() { // creating object Program obj = new Program(); // it will give error Console.WriteLine("The value of b is = " + Program.b); }}
Error:
prog.cs(8,17): error CS0145: A const field requires a value to be provided
Example 2: Program to show the use of constant variables
C#
// C# program to illustrate the// constant variableusing System;class Program { // instance variable int a = 10; // static variable static int b = 20; // constant variable const float max = 50; // Main Method public static void Main() { // creating object Program obj = new Program(); // displaying result Console.WriteLine("The value of a is = " + obj.a); Console.WriteLine("The value of b is = " + Program.b); Console.WriteLine("The value of max is = " + Program.max); }}
Output:
The value of a is = 10
The value of b is = 20
The value of max is = 50
Important Points about Constant Variables:
The behavior of constant variables will be similar to the behavior of static variables i.e. initialized one and only one time in the life cycle of a class and doesn’t require the instance of the class for accessing or initializing.
The difference between a static and constant variable is, static variables can be modified whereas constant variables can’t be modified once it declared.
If a variable is declared by using the readonly keyword then it will be read-only variables and these variables can’t be modified like constants but after initialization.
It’s not compulsory to initialize a read-only variable at the time of the declaration, they can also be initialized under the constructor.
The behavior of read-only variables will be similar to the behavior of non-static variables, i.e. initialized only after creating the instance of the class and once for each instance of the class created.
Example 1: In below program, read-only variables k is not initialized with any value but when we print the value of the variable the default value of int i.e 0 will display as follows :
C#
// C# program to show the use// of readonly variables// without initializing itusing System;class Program { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // Main Method public static void Main() { // Creating object Program obj = new Program(); Console.WriteLine("The value of a is = " + obj.a); Console.WriteLine("The value of b is = " + Program.b); Console.WriteLine("The value of max is = " + Program.max); Console.WriteLine("The value of k is = " + obj.k); }}
Output:
The value of a is = 80
The value of b is = 40
The value of max is = 50
The value of k is = 0
Example 2: To show the initialization of readonly variable in the constructor.
C#
// C# program to illustrate the// initialization of readonly// variables in the constructorusing System;class Geeks { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // constructor public Geeks() { // initializing readonly // variable k this.k = 90; } // Main Method public static void Main() { // Creating object Geeks obj = new Geeks(); Console.WriteLine("The value of a is = " + obj.a); Console.WriteLine("The value of b is = " + Geeks.b); Console.WriteLine("The value of max is = " + Geeks.max); Console.WriteLine("The value of k is = " + obj.k); }}
Output :
The value of a is = 80
The value of b is = 40
The value of max is = 50
The value of k is = 90
Example 3: Program to demonstrate when the readonly variable is initialized after its declaration and outside constructor :
C#
// C# program to illustrate the// initialization of readonly// variables twiceusing System;class Geeks { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // constructor public Geeks() { // first time initializing // readonly variable k this.k = 90; } // Main Method public static void Main() { // Creating object Geeks obj = new Geeks(); Console.WriteLine("The value of a is = " + obj.a); Console.WriteLine("The value of b is = " + Geeks.b); Console.WriteLine("The value of max is = " + Geeks.max); // initializing readonly variable again // will compile time error obj.k = 55; Console.WriteLine("The value of k is = " + obj.k); }}
Error:
prog.cs(41,13): error CS0191: A readonly field `Geeks.k’ cannot be assigned to (except in a constructor or a variable initializer)
Important Points about Read-Only Variables:
The only difference between read-only and instance variables is that the instance variables can be modified but read-only variable can’t be modified.
Constant variable is a fixed value for the whole class whereas read-only variables is a fixed value specific to an instance of class.
Akanksha_Rai
shubham_singh
clintra
surinderdawra388
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Constructors
Difference between Ref and Out keywords in C#
C# | Delegates
Introduction to .NET Framework
Partial Classes in C#
Extension Method in C#
C# | Class and Object
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
C# | Encapsulation
Top 50 C# Interview Questions & Answers | [
{
"code": null,
"e": 24056,
"s": 24028,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 24364,
"s": 24056,
"text": "A variable is a name given to a memory location and all the operations done on the variable effects that memory location. In C#, all the variables must be declared before they can be used. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. "
},
{
"code": null,
"e": 24380,
"s": 24364,
"text": "Local variables"
},
{
"code": null,
"e": 24425,
"s": 24380,
"text": "Instance variables or Non – Static Variables"
},
{
"code": null,
"e": 24461,
"s": 24425,
"text": "Static Variables or Class Variables"
},
{
"code": null,
"e": 24480,
"s": 24461,
"text": "Constant Variables"
},
{
"code": null,
"e": 24500,
"s": 24480,
"text": "Readonly Variables "
},
{
"code": null,
"e": 24587,
"s": 24500,
"text": "A variable defined within a block or method or constructor is called local variable. "
},
{
"code": null,
"e": 24754,
"s": 24587,
"text": "These variables are created when the block is entered or the function is called and destroyed after exiting from the block or when the call returns from the function."
},
{
"code": null,
"e": 24906,
"s": 24754,
"text": "The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variables only within that block."
},
{
"code": null,
"e": 24918,
"s": 24906,
"text": "Example 1: "
},
{
"code": null,
"e": 24921,
"s": 24918,
"text": "C#"
},
{
"code": "// C# program to demonstrate// the local variablesusing System;class StudentDetails { // Method public void StudentAge() { // local variable age int age = 0; age = age + 10; Console.WriteLine(\"Student age is : \" + age); } // Main Method public static void Main(String[] args) { // Creating object StudentDetails obj = new StudentDetails(); // calling the function obj.StudentAge(); }}",
"e": 25428,
"s": 24921,
"text": null
},
{
"code": null,
"e": 25437,
"s": 25428,
"text": "Output: "
},
{
"code": null,
"e": 25457,
"s": 25437,
"text": "Student age is : 10"
},
{
"code": null,
"e": 25681,
"s": 25457,
"text": "Explanation :In the above program, the variable “age” is a local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error as shown in below program."
},
{
"code": null,
"e": 25693,
"s": 25681,
"text": "Example 2: "
},
{
"code": null,
"e": 25696,
"s": 25693,
"text": "C#"
},
{
"code": "// C# program to demonstrate the error// due to using the local variable// outside its scopeusing System; class StudentDetails { // Method public void StudentAge() { // local variable age int age = 0; age = age + 10; } // Main Method public static void Main(String[] args) { // using local variable age outside it's scope Console.WriteLine(\"Student age is : \" + age); }}",
"e": 26150,
"s": 25696,
"text": null
},
{
"code": null,
"e": 26157,
"s": 26150,
"text": "Error:"
},
{
"code": null,
"e": 26240,
"s": 26157,
"text": "prog.cs(22,43): error CS0103: The name `age’ does not exist in the current context"
},
{
"code": null,
"e": 26593,
"s": 26240,
"text": "Instance variables are non-static variables and are declared in a class but outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables."
},
{
"code": null,
"e": 26603,
"s": 26593,
"text": "Example: "
},
{
"code": null,
"e": 26606,
"s": 26603,
"text": "C#"
},
{
"code": "// C# program to illustrate the// Instance variablesusing System; class Marks { // These variables are instance variables. // These variables are in a class and // are not inside any function int engMarks; int mathsMarks; int phyMarks; // Main Method public static void Main(String[] args) { // first object Marks obj1 = new Marks(); obj1.engMarks = 90; obj1.mathsMarks = 80; obj1.phyMarks = 93; // second object Marks obj2 = new Marks(); obj2.engMarks = 95; obj2.mathsMarks = 70; obj2.phyMarks = 90; // displaying marks for first object Console.WriteLine(\"Marks for first object:\"); Console.WriteLine(obj1.engMarks); Console.WriteLine(obj1.mathsMarks); Console.WriteLine(obj1.phyMarks); // displaying marks for second object Console.WriteLine(\"Marks for second object:\"); Console.WriteLine(obj2.engMarks); Console.WriteLine(obj2.mathsMarks); Console.WriteLine(obj2.phyMarks); }}",
"e": 27674,
"s": 26606,
"text": null
},
{
"code": null,
"e": 27684,
"s": 27674,
"text": "Output : "
},
{
"code": null,
"e": 27751,
"s": 27684,
"text": "Marks for first object:\n90\n80\n93\nMarks for second object:\n95\n70\n90"
},
{
"code": null,
"e": 28069,
"s": 27751,
"text": "Explanation: In the above program the variables, engMarks, mathsMarks, phyMarksare instance variables. If there are multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of the instance variable."
},
{
"code": null,
"e": 28288,
"s": 28069,
"text": "Static variables are also known as Class variables. If a variable is explicitly declared with the static modifier or if a variable is declared under any static block then these variables are known as static variables. "
},
{
"code": null,
"e": 28484,
"s": 28288,
"text": "These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block."
},
{
"code": null,
"e": 28612,
"s": 28484,
"text": "Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create."
},
{
"code": null,
"e": 28724,
"s": 28612,
"text": "Static variables are created at the start of program execution and destroyed automatically when execution ends."
},
{
"code": null,
"e": 28843,
"s": 28724,
"text": "Note: To access static variables, there is no need to create any object of that class, simply access the variable as: "
},
{
"code": null,
"e": 28869,
"s": 28843,
"text": "class_name.variable_name;"
},
{
"code": null,
"e": 28879,
"s": 28869,
"text": "Example: "
},
{
"code": null,
"e": 28882,
"s": 28879,
"text": "C#"
},
{
"code": "// C# program to illustrate// the static variablesusing System;class Emp { // static variable salary static double salary; static String name = \"Aks\"; // Main Method public static void Main(String[] args) { // accessing static variable // without object Emp.salary = 100000; Console.WriteLine(Emp.name + \"'s average salary:\" + Emp.salary); }}",
"e": 29328,
"s": 28882,
"text": null
},
{
"code": null,
"e": 29337,
"s": 29328,
"text": "Output: "
},
{
"code": null,
"e": 29365,
"s": 29337,
"text": "Aks's average salary:100000"
},
{
"code": null,
"e": 29692,
"s": 29365,
"text": "Note: Initialization of non-static variables is associated with instance creation and constructor calls, so non-static variables can be initialized through the constructor also. We don’t initialize a static variable through constructor because every time constructor call, it will override the existing value with a new value."
},
{
"code": null,
"e": 29857,
"s": 29692,
"text": "Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create."
},
{
"code": null,
"e": 30127,
"s": 29857,
"text": "Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all object of a class."
},
{
"code": null,
"e": 30250,
"s": 30127,
"text": "We can access instance variables through object references and Static Variables can be accessed directly using class name."
},
{
"code": null,
"e": 30456,
"s": 30250,
"text": "In the life cycle of a class a static variable ie initialized one and only one time, whereas instance variables are initialized for 0 times if no instance is created and n times if n instances are created."
},
{
"code": null,
"e": 30507,
"s": 30456,
"text": "The Syntax for static and instance variables are :"
},
{
"code": null,
"e": 30636,
"s": 30507,
"text": " class Example\n {\n static int a; // static variable\n int b; // instance variable\n }\n "
},
{
"code": null,
"e": 30856,
"s": 30636,
"text": "If a variable is declared by using the keyword “const” then it as a constant variable and these constant variables can’t be modified once after their declaration, so it’s must initialize at the time of declaration only."
},
{
"code": null,
"e": 30977,
"s": 30856,
"text": "Example 1: Below program will show the error because no value is provided at the time of constant variable declaration. "
},
{
"code": null,
"e": 30980,
"s": 30977,
"text": "C#"
},
{
"code": "// C# program to illustrate the// constant variablesusing System;class Program { // constant variable max // but no value is provided const float max; // Main Method public static void Main() { // creating object Program obj = new Program(); // it will give error Console.WriteLine(\"The value of b is = \" + Program.b); }}",
"e": 31372,
"s": 30980,
"text": null
},
{
"code": null,
"e": 31379,
"s": 31372,
"text": "Error:"
},
{
"code": null,
"e": 31456,
"s": 31379,
"text": "prog.cs(8,17): error CS0145: A const field requires a value to be provided "
},
{
"code": null,
"e": 31515,
"s": 31456,
"text": "Example 2: Program to show the use of constant variables "
},
{
"code": null,
"e": 31518,
"s": 31515,
"text": "C#"
},
{
"code": "// C# program to illustrate the// constant variableusing System;class Program { // instance variable int a = 10; // static variable static int b = 20; // constant variable const float max = 50; // Main Method public static void Main() { // creating object Program obj = new Program(); // displaying result Console.WriteLine(\"The value of a is = \" + obj.a); Console.WriteLine(\"The value of b is = \" + Program.b); Console.WriteLine(\"The value of max is = \" + Program.max); }}",
"e": 32090,
"s": 31518,
"text": null
},
{
"code": null,
"e": 32099,
"s": 32090,
"text": "Output: "
},
{
"code": null,
"e": 32170,
"s": 32099,
"text": "The value of a is = 10\nThe value of b is = 20\nThe value of max is = 50"
},
{
"code": null,
"e": 32215,
"s": 32170,
"text": "Important Points about Constant Variables: "
},
{
"code": null,
"e": 32447,
"s": 32215,
"text": "The behavior of constant variables will be similar to the behavior of static variables i.e. initialized one and only one time in the life cycle of a class and doesn’t require the instance of the class for accessing or initializing."
},
{
"code": null,
"e": 32601,
"s": 32447,
"text": "The difference between a static and constant variable is, static variables can be modified whereas constant variables can’t be modified once it declared."
},
{
"code": null,
"e": 32773,
"s": 32601,
"text": "If a variable is declared by using the readonly keyword then it will be read-only variables and these variables can’t be modified like constants but after initialization. "
},
{
"code": null,
"e": 32912,
"s": 32773,
"text": "It’s not compulsory to initialize a read-only variable at the time of the declaration, they can also be initialized under the constructor."
},
{
"code": null,
"e": 33117,
"s": 32912,
"text": "The behavior of read-only variables will be similar to the behavior of non-static variables, i.e. initialized only after creating the instance of the class and once for each instance of the class created."
},
{
"code": null,
"e": 33303,
"s": 33117,
"text": "Example 1: In below program, read-only variables k is not initialized with any value but when we print the value of the variable the default value of int i.e 0 will display as follows :"
},
{
"code": null,
"e": 33306,
"s": 33303,
"text": "C#"
},
{
"code": "// C# program to show the use// of readonly variables// without initializing itusing System;class Program { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // Main Method public static void Main() { // Creating object Program obj = new Program(); Console.WriteLine(\"The value of a is = \" + obj.a); Console.WriteLine(\"The value of b is = \" + Program.b); Console.WriteLine(\"The value of max is = \" + Program.max); Console.WriteLine(\"The value of k is = \" + obj.k); }}",
"e": 33986,
"s": 33306,
"text": null
},
{
"code": null,
"e": 33995,
"s": 33986,
"text": "Output: "
},
{
"code": null,
"e": 34088,
"s": 33995,
"text": "The value of a is = 80\nThe value of b is = 40\nThe value of max is = 50\nThe value of k is = 0"
},
{
"code": null,
"e": 34167,
"s": 34088,
"text": "Example 2: To show the initialization of readonly variable in the constructor."
},
{
"code": null,
"e": 34170,
"s": 34167,
"text": "C#"
},
{
"code": "// C# program to illustrate the// initialization of readonly// variables in the constructorusing System;class Geeks { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // constructor public Geeks() { // initializing readonly // variable k this.k = 90; } // Main Method public static void Main() { // Creating object Geeks obj = new Geeks(); Console.WriteLine(\"The value of a is = \" + obj.a); Console.WriteLine(\"The value of b is = \" + Geeks.b); Console.WriteLine(\"The value of max is = \" + Geeks.max); Console.WriteLine(\"The value of k is = \" + obj.k); }}",
"e": 34965,
"s": 34170,
"text": null
},
{
"code": null,
"e": 34975,
"s": 34965,
"text": "Output : "
},
{
"code": null,
"e": 35069,
"s": 34975,
"text": "The value of a is = 80\nThe value of b is = 40\nThe value of max is = 50\nThe value of k is = 90"
},
{
"code": null,
"e": 35193,
"s": 35069,
"text": "Example 3: Program to demonstrate when the readonly variable is initialized after its declaration and outside constructor :"
},
{
"code": null,
"e": 35196,
"s": 35193,
"text": "C#"
},
{
"code": "// C# program to illustrate the// initialization of readonly// variables twiceusing System;class Geeks { // instance variable int a = 80; // static variable static int b = 40; // Constant variables const float max = 50; // readonly variables readonly int k; // constructor public Geeks() { // first time initializing // readonly variable k this.k = 90; } // Main Method public static void Main() { // Creating object Geeks obj = new Geeks(); Console.WriteLine(\"The value of a is = \" + obj.a); Console.WriteLine(\"The value of b is = \" + Geeks.b); Console.WriteLine(\"The value of max is = \" + Geeks.max); // initializing readonly variable again // will compile time error obj.k = 55; Console.WriteLine(\"The value of k is = \" + obj.k); }}",
"e": 36091,
"s": 35196,
"text": null
},
{
"code": null,
"e": 36098,
"s": 36091,
"text": "Error:"
},
{
"code": null,
"e": 36231,
"s": 36098,
"text": "prog.cs(41,13): error CS0191: A readonly field `Geeks.k’ cannot be assigned to (except in a constructor or a variable initializer) "
},
{
"code": null,
"e": 36276,
"s": 36231,
"text": "Important Points about Read-Only Variables: "
},
{
"code": null,
"e": 36426,
"s": 36276,
"text": "The only difference between read-only and instance variables is that the instance variables can be modified but read-only variable can’t be modified."
},
{
"code": null,
"e": 36560,
"s": 36426,
"text": "Constant variable is a fixed value for the whole class whereas read-only variables is a fixed value specific to an instance of class."
},
{
"code": null,
"e": 36573,
"s": 36560,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 36587,
"s": 36573,
"text": "shubham_singh"
},
{
"code": null,
"e": 36595,
"s": 36587,
"text": "clintra"
},
{
"code": null,
"e": 36612,
"s": 36595,
"text": "surinderdawra388"
},
{
"code": null,
"e": 36626,
"s": 36612,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 36629,
"s": 36626,
"text": "C#"
},
{
"code": null,
"e": 36727,
"s": 36629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36736,
"s": 36727,
"text": "Comments"
},
{
"code": null,
"e": 36749,
"s": 36736,
"text": "Old Comments"
},
{
"code": null,
"e": 36767,
"s": 36749,
"text": "C# | Constructors"
},
{
"code": null,
"e": 36813,
"s": 36767,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 36828,
"s": 36813,
"text": "C# | Delegates"
},
{
"code": null,
"e": 36859,
"s": 36828,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 36881,
"s": 36859,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 36904,
"s": 36881,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 36926,
"s": 36904,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 37013,
"s": 36926,
"text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework"
},
{
"code": null,
"e": 37032,
"s": 37013,
"text": "C# | Encapsulation"
}
]
|
Java switch statement with multiple cases. | Following is the required program.
Live Demo
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0); char grade = 'C'; switch(grade) {
case 'A' : System.out.println("Excellent!"); break;
case 'B' :
case 'C' : System.out.println("Well done");
break;
case 'D' : System.out.println("You passed");
case 'F' : System.out.println("Better try again");
break;
default : System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run the above program using various command line arguments. This will produce the following result −
Well done
Your grade is C | [
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1649,
"s": 1107,
"text": "public class Test {\n public static void main(String args[]) {\n // char grade = args[0].charAt(0); char grade = 'C'; switch(grade) {\n case 'A' : System.out.println(\"Excellent!\"); break;\n case 'B' :\n case 'C' : System.out.println(\"Well done\");\n break;\n case 'D' : System.out.println(\"You passed\");\n case 'F' : System.out.println(\"Better try again\");\n break;\n default : System.out.println(\"Invalid grade\");\n }\n System.out.println(\"Your grade is \" + grade);\n }\n}"
},
{
"code": null,
"e": 1762,
"s": 1649,
"text": "Compile and run the above program using various command line arguments. This will produce the following result −"
},
{
"code": null,
"e": 1788,
"s": 1762,
"text": "Well done\nYour grade is C"
}
]
|
How to center align text in table cells in HTML? | To center align text in table cells, use the CSS property text-align. The <table> tag align attribute was used before, but HTML5 deprecated the attribute. Do not use it. So, use CSS to align text in table cells. The text-align will be used for the <td> tag.
We’re using the style attribute for adding CSS. The style attribute specifies an inline style for an element. The attribute is used with the HTML <td> tag, with the CSS property text-align. HTML5 do not support the align tag,
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
For text-align, set the table cell as left, right or center align
You can try to run the following code to center align text in table cells in HTML
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid black;
width: 300px;
}
</style>
</head>
<body>
<h1>Our Technologies</h1>
<table>
<tr>
<th>IDE</th>
<th>Database</th>
</tr>
<tr>
<td style="text-align:center">NetBeans</td>
<td style="text-align:center">MySQL</td>
</tr>
</table>
</body>
</html> | [
{
"code": null,
"e": 1320,
"s": 1062,
"text": "To center align text in table cells, use the CSS property text-align. The <table> tag align attribute was used before, but HTML5 deprecated the attribute. Do not use it. So, use CSS to align text in table cells. The text-align will be used for the <td> tag."
},
{
"code": null,
"e": 1546,
"s": 1320,
"text": "We’re using the style attribute for adding CSS. The style attribute specifies an inline style for an element. The attribute is used with the HTML <td> tag, with the CSS property text-align. HTML5 do not support the align tag,"
},
{
"code": null,
"e": 1708,
"s": 1546,
"text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet."
},
{
"code": null,
"e": 1774,
"s": 1708,
"text": "For text-align, set the table cell as left, right or center align"
},
{
"code": null,
"e": 1856,
"s": 1774,
"text": "You can try to run the following code to center align text in table cells in HTML"
},
{
"code": null,
"e": 2340,
"s": 1856,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, td, th {\n border: 1px solid black;\n width: 300px;\n }\n </style>\n </head>\n <body>\n <h1>Our Technologies</h1>\n <table>\n <tr>\n <th>IDE</th>\n <th>Database</th>\n </tr>\n <tr>\n <td style=\"text-align:center\">NetBeans</td>\n <td style=\"text-align:center\">MySQL</td>\n </tr>\n </table>\n </body>\n</html>"
}
]
|
Insertion Sort in Python Program | In this article, we will learn about the implementation of Insertion sort in Python 3.x. Or earlier.
Iterate over the input elements by growing the sorted array at each iteration.
Iterate over the input elements by growing the sorted array at each iteration.
Compare the current element with the largest value available in the sorted array.
Compare the current element with the largest value available in the sorted array.
If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array.
If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array.
This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead.
This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead.
Now let’s see the visual representation of the algorithm
Now let’s see the implementation
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greater
than key,
# to one position ahead of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# main
arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
print ("The sorted array is:")
for i in range(len(arr)):
print (arr[i])
The sorted array is:
a
i
l
o
r
t
t
u
Time Complexity: O(n*2)
Auxiliary Space: O(1)
All the variables are declared in the global frame as shown in the figure below −
In this article, we learnt about the Insertion sort and its implementation in Python 3.x. or earlier. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we will learn about the implementation of Insertion sort in Python 3.x. Or earlier."
},
{
"code": null,
"e": 1242,
"s": 1163,
"text": "Iterate over the input elements by growing the sorted array at each iteration."
},
{
"code": null,
"e": 1321,
"s": 1242,
"text": "Iterate over the input elements by growing the sorted array at each iteration."
},
{
"code": null,
"e": 1403,
"s": 1321,
"text": "Compare the current element with the largest value available in the sorted array."
},
{
"code": null,
"e": 1485,
"s": 1403,
"text": "Compare the current element with the largest value available in the sorted array."
},
{
"code": null,
"e": 1692,
"s": 1485,
"text": "If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array."
},
{
"code": null,
"e": 1899,
"s": 1692,
"text": "If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array."
},
{
"code": null,
"e": 2050,
"s": 1899,
"text": "This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead."
},
{
"code": null,
"e": 2201,
"s": 2050,
"text": "This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead."
},
{
"code": null,
"e": 2258,
"s": 2201,
"text": "Now let’s see the visual representation of the algorithm"
},
{
"code": null,
"e": 2291,
"s": 2258,
"text": "Now let’s see the implementation"
},
{
"code": null,
"e": 2749,
"s": 2291,
"text": "def insertionSort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n # Move elements of arr[0..i-1], that are greater\n than key,\n # to one position ahead of their current position\n j = i-1\n while j >=0 and key < arr[j] :\n arr[j+1] = arr[j]\n j -= 1\n arr[j+1] = key\n# main\narr = ['t','u','t','o','r','i','a','l']\ninsertionSort(arr)\nprint (\"The sorted array is:\")\nfor i in range(len(arr)):\n print (arr[i])"
},
{
"code": null,
"e": 2786,
"s": 2749,
"text": "The sorted array is:\na\ni\nl\no\nr\nt\nt\nu"
},
{
"code": null,
"e": 2810,
"s": 2786,
"text": "Time Complexity: O(n*2)"
},
{
"code": null,
"e": 2832,
"s": 2810,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2914,
"s": 2832,
"text": "All the variables are declared in the global frame as shown in the figure below −"
},
{
"code": null,
"e": 3016,
"s": 2914,
"text": "In this article, we learnt about the Insertion sort and its implementation in Python 3.x. or earlier."
}
]
|
How and why to avoid global variables in JavaScript? | Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn’t overwrite values of another variable.
On the usage of more global variables in our code, it may lead to a maintenance issue. Let’s say we added a variable with the same name. In that case, get ready for some serious bugs.
To avoid the usage of global variables, use the local variables and wrap your code in closures. You can also avoid this by wrapping the variables with json −
var wrapperDemo= {
x:5,
y:function(myObj){
}
};
Above, if you want to call x, then call it using −
wrapperDemo. | [
{
"code": null,
"e": 1333,
"s": 1062,
"text": "Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn’t overwrite values of another variable."
},
{
"code": null,
"e": 1517,
"s": 1333,
"text": "On the usage of more global variables in our code, it may lead to a maintenance issue. Let’s say we added a variable with the same name. In that case, get ready for some serious bugs."
},
{
"code": null,
"e": 1675,
"s": 1517,
"text": "To avoid the usage of global variables, use the local variables and wrap your code in closures. You can also avoid this by wrapping the variables with json −"
},
{
"code": null,
"e": 1732,
"s": 1675,
"text": "var wrapperDemo= {\n x:5,\n y:function(myObj){\n }\n};"
},
{
"code": null,
"e": 1783,
"s": 1732,
"text": "Above, if you want to call x, then call it using −"
},
{
"code": null,
"e": 1796,
"s": 1783,
"text": "wrapperDemo."
}
]
|
How to access the fields of an interface in Java? | An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface. By default,
All the members (methods and fields) of an interface are public.
All the members (methods and fields) of an interface are public.
All the methods in an interface are public and abstract (except static and default).
All the methods in an interface are public and abstract (except static and default).
All the fields of an interface are public, static and, final by default.
All the fields of an interface are public, static and, final by default.
If you declare/define fields without public or, static or, final or, all the three modifiers. Java compiler places them on your behalf.
In the following Java program, we are having a filed without public or, static or, final modifiers.
public interface MyInterface{
int num =40;
void demo();
}
If you compile this using the javac command as shown below −
c:\Examples>javac MyInterface.java
It gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −
c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
public static final int num;
public abstract void demo();
}
In general, to create an object of an interface type you need to implement it and provide implementation to all the abstract methods in it. When you do so, all the fields of the interface are inherited by the implementing class, i.e. a copy of the fields of an interface are available in the class that implements it.
Since all the fields of an interface are static by default, you can access them using the name of the interface as −
Live Demo
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
System.out.println("Value of num of the interface "+MyInterface.num);
System.out.println("Value of num of the class "+obj.num);
}
}
Value of num of the interface 100
Value of num of the class 10000
But, since the variables of an interface are final you cannot reassign values to them. If you try to do so, a compile-time error will be generated.
Live Demo
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public static int num = 10000;
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
MyInterface.num = 200;
}
}
InterfaceExample.java:14: error: cannot assign a value to final variable num
MyInterface.num = 200;
^
1 error | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface. By default,"
},
{
"code": null,
"e": 1350,
"s": 1285,
"text": "All the members (methods and fields) of an interface are public."
},
{
"code": null,
"e": 1415,
"s": 1350,
"text": "All the members (methods and fields) of an interface are public."
},
{
"code": null,
"e": 1500,
"s": 1415,
"text": "All the methods in an interface are public and abstract (except static and default)."
},
{
"code": null,
"e": 1585,
"s": 1500,
"text": "All the methods in an interface are public and abstract (except static and default)."
},
{
"code": null,
"e": 1658,
"s": 1585,
"text": "All the fields of an interface are public, static and, final by default."
},
{
"code": null,
"e": 1731,
"s": 1658,
"text": "All the fields of an interface are public, static and, final by default."
},
{
"code": null,
"e": 1867,
"s": 1731,
"text": "If you declare/define fields without public or, static or, final or, all the three modifiers. Java compiler places them on your behalf."
},
{
"code": null,
"e": 1967,
"s": 1867,
"text": "In the following Java program, we are having a filed without public or, static or, final modifiers."
},
{
"code": null,
"e": 2031,
"s": 1967,
"text": "public interface MyInterface{\n int num =40;\n void demo();\n}"
},
{
"code": null,
"e": 2092,
"s": 2031,
"text": "If you compile this using the javac command as shown below −"
},
{
"code": null,
"e": 2127,
"s": 2092,
"text": "c:\\Examples>javac MyInterface.java"
},
{
"code": null,
"e": 2252,
"s": 2127,
"text": "It gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −"
},
{
"code": null,
"e": 2412,
"s": 2252,
"text": "c:\\Examples>javap MyInterface\nCompiled from \"MyInterface.java\"\npublic interface MyInterface {\n public static final int num;\n public abstract void demo();\n}"
},
{
"code": null,
"e": 2730,
"s": 2412,
"text": "In general, to create an object of an interface type you need to implement it and provide implementation to all the abstract methods in it. When you do so, all the fields of the interface are inherited by the implementing class, i.e. a copy of the fields of an interface are available in the class that implements it."
},
{
"code": null,
"e": 2847,
"s": 2730,
"text": "Since all the fields of an interface are static by default, you can access them using the name of the interface as −"
},
{
"code": null,
"e": 2858,
"s": 2847,
"text": " Live Demo"
},
{
"code": null,
"e": 3487,
"s": 2858,
"text": "interface MyInterface{\n public static int num = 100;\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public static int num = 10000;\n public void display() {\n System.out.println(\"This is the implementation of the display method\");\n }\n public void show() {\n System.out.println(\"This is the implementation of the show method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n System.out.println(\"Value of num of the interface \"+MyInterface.num);\n System.out.println(\"Value of num of the class \"+obj.num);\n }\n}"
},
{
"code": null,
"e": 3553,
"s": 3487,
"text": "Value of num of the interface 100\nValue of num of the class 10000"
},
{
"code": null,
"e": 3701,
"s": 3553,
"text": "But, since the variables of an interface are final you cannot reassign values to them. If you try to do so, a compile-time error will be generated."
},
{
"code": null,
"e": 3712,
"s": 3701,
"text": " Live Demo"
},
{
"code": null,
"e": 4177,
"s": 3712,
"text": "interface MyInterface{\n public static int num = 100;\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public static int num = 10000;\n public void display() {\n System.out.println(\"This is the implementation of the display method\");\n }\n public void show() {\n System.out.println(\"This is the implementation of the show method\");\n }\n public static void main(String args[]) {\n MyInterface.num = 200;\n }\n}"
},
{
"code": null,
"e": 4305,
"s": 4177,
"text": "InterfaceExample.java:14: error: cannot assign a value to final variable num\n MyInterface.num = 200;\n ^\n1 error"
}
]
|
C++ Program to Find a triplet such that sum of two equals to third element - GeeksforGeeks | 11 Jan, 2022
Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element.Examples:
Input: {5, 32, 1, 7, 10, 50, 19, 21, 2}
Output: 21, 2, 19
Input: {5, 32, 1, 7, 10, 50, 19, 21, 0}
Output: no such triplet exist
Question source: Arcesium Interview Experience | Set 7 (On campus for Internship)
Simple approach: Run three loops and check if there exists a triplet such that sum of two elements equals the third element.Time complexity: O(n^3)Efficient approach: The idea is similar to Find a triplet that sum to a given value.
Sort the given array first.
Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element.
Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers
If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k].
If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k].
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
// C++ program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>using namespace std; // Utility function for finding// triplet in arrayvoid findTriplet(int arr[], int n){ // Sort the array sort(arr, arr + n); // For every element in arr check // if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; // Iterate forward and backward to // find the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // Pair found cout << "numbers are " << arr[i] << " " << arr[j] << " " << arr[k] << endl; return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array cout << "No such triplet exists";} // Driver codeint main(){ int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2}; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;}
Output:
numbers are 21 2 19
Time complexity: O(N^2)
Another Approach: The idea is similar to previous approach.
Sort the given array.Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).Take the sum of both the elements and search it in the remaining array using Binary Search.
Sort the given array.
Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).
Take the sum of both the elements and search it in the remaining array using Binary Search.
C++
// C++ program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>#include <iostream>using namespace std; // Function to perform binary searchbool search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Function to find the tripletsvoid findTriplet(int arr[], int n){ // Sorting the array sort(arr, arr + n); // Initialising nested loops for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // Printing out the first triplet cout << "Numbers are: " << arr[i] << " " << arr[j] << " " << (arr[i] + arr[j]); return; } } } // If no such triplets are found cout << "No such numbers exist" << endl;} // Driver codeint main(){ int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2}; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;}// This code is contributed by Sarthak Delori
Time Complexity: O(N^2*log N)
Space Complexity: O(1)
Please refer complete article on Find a triplet such that sum of two equals to third element for more details!
Amazon
Arcesium
two-pointer-algorithm
Arrays
C++
C++ Programs
Searching
Amazon
Arcesium
two-pointer-algorithm
Arrays
Searching
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array of size n and a number k, find all elements that appear more than n/k times
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 24387,
"s": 24359,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 24515,
"s": 24387,
"text": "Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element.Examples:"
},
{
"code": null,
"e": 24644,
"s": 24515,
"text": "Input: {5, 32, 1, 7, 10, 50, 19, 21, 2}\nOutput: 21, 2, 19\n\nInput: {5, 32, 1, 7, 10, 50, 19, 21, 0}\nOutput: no such triplet exist"
},
{
"code": null,
"e": 24726,
"s": 24644,
"text": "Question source: Arcesium Interview Experience | Set 7 (On campus for Internship)"
},
{
"code": null,
"e": 24958,
"s": 24726,
"text": "Simple approach: Run three loops and check if there exists a triplet such that sum of two elements equals the third element.Time complexity: O(n^3)Efficient approach: The idea is similar to Find a triplet that sum to a given value."
},
{
"code": null,
"e": 24986,
"s": 24958,
"text": "Sort the given array first."
},
{
"code": null,
"e": 25131,
"s": 24986,
"text": "Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element."
},
{
"code": null,
"e": 25285,
"s": 25131,
"text": "Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers"
},
{
"code": null,
"e": 25492,
"s": 25285,
"text": "If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k]."
},
{
"code": null,
"e": 25698,
"s": 25492,
"text": "If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k]."
},
{
"code": null,
"e": 25746,
"s": 25698,
"text": "Below image is a dry run of the above approach:"
},
{
"code": null,
"e": 25797,
"s": 25746,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25801,
"s": 25797,
"text": "C++"
},
{
"code": "// C++ program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>using namespace std; // Utility function for finding// triplet in arrayvoid findTriplet(int arr[], int n){ // Sort the array sort(arr, arr + n); // For every element in arr check // if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; // Iterate forward and backward to // find the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // Pair found cout << \"numbers are \" << arr[i] << \" \" << arr[j] << \" \" << arr[k] << endl; return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array cout << \"No such triplet exists\";} // Driver codeint main(){ int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2}; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;}",
"e": 27400,
"s": 25801,
"text": null
},
{
"code": null,
"e": 27410,
"s": 27400,
"text": "Output: "
},
{
"code": null,
"e": 27430,
"s": 27410,
"text": "numbers are 21 2 19"
},
{
"code": null,
"e": 27454,
"s": 27430,
"text": "Time complexity: O(N^2)"
},
{
"code": null,
"e": 27514,
"s": 27454,
"text": "Another Approach: The idea is similar to previous approach."
},
{
"code": null,
"e": 27735,
"s": 27514,
"text": "Sort the given array.Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).Take the sum of both the elements and search it in the remaining array using Binary Search."
},
{
"code": null,
"e": 27757,
"s": 27735,
"text": "Sort the given array."
},
{
"code": null,
"e": 27866,
"s": 27757,
"text": "Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1)."
},
{
"code": null,
"e": 27958,
"s": 27866,
"text": "Take the sum of both the elements and search it in the remaining array using Binary Search."
},
{
"code": null,
"e": 27962,
"s": 27958,
"text": "C++"
},
{
"code": "// C++ program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>#include <iostream>using namespace std; // Function to perform binary searchbool search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Function to find the tripletsvoid findTriplet(int arr[], int n){ // Sorting the array sort(arr, arr + n); // Initialising nested loops for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // Printing out the first triplet cout << \"Numbers are: \" << arr[i] << \" \" << arr[j] << \" \" << (arr[i] + arr[j]); return; } } } // If no such triplets are found cout << \"No such numbers exist\" << endl;} // Driver codeint main(){ int arr[] = {5, 32, 1, 7, 10, 50, 19, 21, 2}; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;}// This code is contributed by Sarthak Delori",
"e": 29426,
"s": 27962,
"text": null
},
{
"code": null,
"e": 29456,
"s": 29426,
"text": "Time Complexity: O(N^2*log N)"
},
{
"code": null,
"e": 29480,
"s": 29456,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 29591,
"s": 29480,
"text": "Please refer complete article on Find a triplet such that sum of two equals to third element for more details!"
},
{
"code": null,
"e": 29598,
"s": 29591,
"text": "Amazon"
},
{
"code": null,
"e": 29607,
"s": 29598,
"text": "Arcesium"
},
{
"code": null,
"e": 29629,
"s": 29607,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 29636,
"s": 29629,
"text": "Arrays"
},
{
"code": null,
"e": 29640,
"s": 29636,
"text": "C++"
},
{
"code": null,
"e": 29653,
"s": 29640,
"text": "C++ Programs"
},
{
"code": null,
"e": 29663,
"s": 29653,
"text": "Searching"
},
{
"code": null,
"e": 29670,
"s": 29663,
"text": "Amazon"
},
{
"code": null,
"e": 29679,
"s": 29670,
"text": "Arcesium"
},
{
"code": null,
"e": 29701,
"s": 29679,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 29708,
"s": 29701,
"text": "Arrays"
},
{
"code": null,
"e": 29718,
"s": 29708,
"text": "Searching"
},
{
"code": null,
"e": 29722,
"s": 29718,
"text": "CPP"
},
{
"code": null,
"e": 29820,
"s": 29722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29829,
"s": 29820,
"text": "Comments"
},
{
"code": null,
"e": 29842,
"s": 29829,
"text": "Old Comments"
},
{
"code": null,
"e": 29865,
"s": 29842,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 29897,
"s": 29865,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29918,
"s": 29897,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 29963,
"s": 29918,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 30054,
"s": 29963,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 30100,
"s": 30054,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30143,
"s": 30100,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30166,
"s": 30143,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 30185,
"s": 30166,
"text": "Inheritance in C++"
}
]
|
C - Structures | Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. The following example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
You can pass a structure as a function argument in the same way as you pass any other variable or pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book ) {
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
You can define pointers to structures in the same way as you define pointer to any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the → operator as follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples include −
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For example −
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int.
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields while others would store the next field in the next word.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2299,
"s": 2084,
"text": "Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds."
},
{
"code": null,
"e": 2468,
"s": 2299,
"text": "Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −"
},
{
"code": null,
"e": 2474,
"s": 2468,
"text": "Title"
},
{
"code": null,
"e": 2481,
"s": 2474,
"text": "Author"
},
{
"code": null,
"e": 2489,
"s": 2481,
"text": "Subject"
},
{
"code": null,
"e": 2497,
"s": 2489,
"text": "Book ID"
},
{
"code": null,
"e": 2679,
"s": 2497,
"text": "To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows −"
},
{
"code": null,
"e": 2817,
"s": 2679,
"text": "struct [structure tag] {\n\n member definition;\n member definition;\n ...\n member definition;\n} [one or more structure variables]; "
},
{
"code": null,
"e": 3167,
"s": 2817,
"text": "The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −"
},
{
"code": null,
"e": 3274,
"s": 3167,
"text": "struct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} book; "
},
{
"code": null,
"e": 3621,
"s": 3274,
"text": "To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. The following example shows how to use a structure in a program −"
},
{
"code": null,
"e": 4770,
"s": 3621,
"text": "#include <stdio.h>\n#include <string.h>\n \nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n \nint main( ) {\n\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n strcpy( Book1.title, \"C Programming\");\n strcpy( Book1.author, \"Nuha Ali\"); \n strcpy( Book1.subject, \"C Programming Tutorial\");\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Zara Ali\");\n strcpy( Book2.subject, \"Telecom Billing Tutorial\");\n Book2.book_id = 6495700;\n \n /* print Book1 info */\n printf( \"Book 1 title : %s\\n\", Book1.title);\n printf( \"Book 1 author : %s\\n\", Book1.author);\n printf( \"Book 1 subject : %s\\n\", Book1.subject);\n printf( \"Book 1 book_id : %d\\n\", Book1.book_id);\n\n /* print Book2 info */\n printf( \"Book 2 title : %s\\n\", Book2.title);\n printf( \"Book 2 author : %s\\n\", Book2.author);\n printf( \"Book 2 subject : %s\\n\", Book2.subject);\n printf( \"Book 2 book_id : %d\\n\", Book2.book_id);\n\n return 0;\n}"
},
{
"code": null,
"e": 4851,
"s": 4770,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5094,
"s": 4851,
"text": "Book 1 title : C Programming\nBook 1 author : Nuha Ali\nBook 1 subject : C Programming Tutorial\nBook 1 book_id : 6495407\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n"
},
{
"code": null,
"e": 5201,
"s": 5094,
"text": "You can pass a structure as a function argument in the same way as you pass any other variable or pointer."
},
{
"code": null,
"e": 6288,
"s": 5201,
"text": "#include <stdio.h>\n#include <string.h>\n \nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n\n/* function declaration */\nvoid printBook( struct Books book );\n\nint main( ) {\n\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n strcpy( Book1.title, \"C Programming\");\n strcpy( Book1.author, \"Nuha Ali\"); \n strcpy( Book1.subject, \"C Programming Tutorial\");\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Zara Ali\");\n strcpy( Book2.subject, \"Telecom Billing Tutorial\");\n Book2.book_id = 6495700;\n \n /* print Book1 info */\n printBook( Book1 );\n\n /* Print Book2 info */\n printBook( Book2 );\n\n return 0;\n}\n\nvoid printBook( struct Books book ) {\n\n printf( \"Book title : %s\\n\", book.title);\n printf( \"Book author : %s\\n\", book.author);\n printf( \"Book subject : %s\\n\", book.subject);\n printf( \"Book book_id : %d\\n\", book.book_id);\n}"
},
{
"code": null,
"e": 6369,
"s": 6288,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6596,
"s": 6369,
"text": "Book title : C Programming\nBook author : Nuha Ali\nBook subject : C Programming Tutorial\nBook book_id : 6495407\nBook title : Telecom Billing\nBook author : Zara Ali\nBook subject : Telecom Billing Tutorial\nBook book_id : 6495700\n"
},
{
"code": null,
"e": 6696,
"s": 6596,
"text": "You can define pointers to structures in the same way as you define pointer to any other variable −"
},
{
"code": null,
"e": 6727,
"s": 6696,
"text": "struct Books *struct_pointer;\n"
},
{
"code": null,
"e": 6931,
"s": 6727,
"text": "Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows −"
},
{
"code": null,
"e": 6956,
"s": 6931,
"text": "struct_pointer = &Book1;"
},
{
"code": null,
"e": 7069,
"s": 6956,
"text": "To access the members of a structure using a pointer to that structure, you must use the → operator as follows −"
},
{
"code": null,
"e": 7092,
"s": 7069,
"text": "struct_pointer->title;"
},
{
"code": null,
"e": 7151,
"s": 7092,
"text": "Let us re-write the above example using structure pointer."
},
{
"code": null,
"e": 8301,
"s": 7151,
"text": "#include <stdio.h>\n#include <string.h>\n \nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n\n/* function declaration */\nvoid printBook( struct Books *book );\nint main( ) {\n\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n strcpy( Book1.title, \"C Programming\");\n strcpy( Book1.author, \"Nuha Ali\"); \n strcpy( Book1.subject, \"C Programming Tutorial\");\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Zara Ali\");\n strcpy( Book2.subject, \"Telecom Billing Tutorial\");\n Book2.book_id = 6495700;\n \n /* print Book1 info by passing address of Book1 */\n printBook( &Book1 );\n\n /* print Book2 info by passing address of Book2 */\n printBook( &Book2 );\n\n return 0;\n}\n\nvoid printBook( struct Books *book ) {\n\n printf( \"Book title : %s\\n\", book->title);\n printf( \"Book author : %s\\n\", book->author);\n printf( \"Book subject : %s\\n\", book->subject);\n printf( \"Book book_id : %d\\n\", book->book_id);\n}"
},
{
"code": null,
"e": 8382,
"s": 8301,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8609,
"s": 8382,
"text": "Book title : C Programming\nBook author : Nuha Ali\nBook subject : C Programming Tutorial\nBook book_id : 6495407\nBook title : Telecom Billing\nBook author : Zara Ali\nBook subject : Telecom Billing Tutorial\nBook book_id : 6495700\n"
},
{
"code": null,
"e": 8760,
"s": 8609,
"text": "Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples include −"
},
{
"code": null,
"e": 8840,
"s": 8760,
"text": "Packing several objects into a machine word. e.g. 1 bit flags can be compacted."
},
{
"code": null,
"e": 8920,
"s": 8840,
"text": "Packing several objects into a machine word. e.g. 1 bit flags can be compacted."
},
{
"code": null,
"e": 9019,
"s": 8920,
"text": "Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers."
},
{
"code": null,
"e": 9118,
"s": 9019,
"text": "Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers."
},
{
"code": null,
"e": 9224,
"s": 9118,
"text": "C allows us to do this in a structure definition by putting :bit length after the variable. For example −"
},
{
"code": null,
"e": 9393,
"s": 9224,
"text": "struct packed_struct {\n unsigned int f1:1;\n unsigned int f2:1;\n unsigned int f3:1;\n unsigned int f4:1;\n unsigned int type:4;\n unsigned int my_int:9;\n} pack;"
},
{
"code": null,
"e": 9495,
"s": 9393,
"text": "Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int."
},
{
"code": null,
"e": 9819,
"s": 9495,
"text": "C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields while others would store the next field in the next word."
},
{
"code": null,
"e": 9826,
"s": 9819,
"text": " Print"
},
{
"code": null,
"e": 9837,
"s": 9826,
"text": " Add Notes"
}
]
|
Boosting your Sequence Generation Performance with ‘Beam-search + Language model’ decoding | by Kartik Chaudhary | Towards Data Science | Whenever Image Processing, Audio data Analysis or Natural language processing (NLP) tasks are concerned, Deep learning has proved to be an ideal choice and has shown outstanding outcomes. Neural Network-based model architectures are really good at understanding complex patterns as well as generating meaningful and realistic data. Although deep learning-based solutions are generally very efficient, it’s never a bad idea to use better post-processing techniques to make predictions even more accurate.
Complex problems such as Neural Machine Translation (NMT), Image caption generation (ICG) and speech recognition (ASR) are very much solvable today using deep learning. These problems are categorized as sequence generation problems where given an input, the model learns to generate some text sequence. If you take a look at the research papers showing state of the art (SOTA) results on these tasks, you will probably find their solution utilizing a beam search decoder fused with a Language model to boost the results. Let’s learn more about these decoding techniques with examples —
Going further, we will define an example sequence generation problem and explore post-processing (decoding) techniques. We will start with a greedy-search-decoding technique and introduce beam-search-decoding fused with language model to further improve the overall results.
Consider a problem of English language text generation and suppose we have already trained a model to do that. Depending upon the nature of the problem or solution strategy, our model might be a character-level model or a word-level model. A character-level text generator model generates text by predicting one character at a time. Similarly, a word-level text generator predicts one word at a time and multiple predicted such words make a sequence.
Assume we have trained a character-level model that generates text by predicting one character at a time. This problem can be related to any of the following problems — Speech to Text, Optical Character Recognition, Image caption generation....etc. Such problems are usually solved using an encoder-decoder architecture as shown in the figure below. The encoder part is responsible for taking an input vector (audio, image or text....) and producing an encoded context vector. The decoder part then uses that context vector to generate the output sequence by predicting one token (char/ wordbbb) at a time.
As our model is character-level, It will generate a probability distribution over all the possible characters for each token in the output sequence. In other words — For each token (char) our model is predicting, it will generate a probability array of length 26 (as per the English language — a to z) and the probabilities will show how likely a particular character is to be the output token.
For a predicted sequence of length 10 (chars), our models' output would look something like this —
output_shape = 10 * 26 output = [[0.1, 0.01, 0.03, ... ... ... ... ... (len-26)], [0.1, 0.002, 0.6, ... ... ... ... ... (len-26)], '' '' '' '' '' '' '' '' '' '' [0.9, 0.01, 0.01, ... ... ... ... ... (len-26)]]
To convert this probabilistic output into a readable form (English text), we need a decoding algorithm. The simplest decoder would be a greedy-search-decoder. Let’s write a greedy-search-decoder along with a complex one called beam-search-decoder —
Note — A sequence generation problem doesn’t necessarily involve text generation, it could be any kind of sequence. We are taking a text generation problem as an example because we are going to talk about language modeling as well in this post.
The simplest way to decode the models’ predictions is to consider the most likely sequence as output. A greedy decoder, also called as the best-path decoder considers the token (character or word) with the highest probability in each prediction and concatenates all the predicted tokens to get the final output sequence. This is a simple and fast way to get the output sequence. But it may not always give you the best output.
Here is how you write a greedy decoder for your model in Python —
Here the shape of the model's prediction is 5*4 that means, the model is trying to generate a sequence of length five. As there are only four different tokens in the vocabulary, the model predicts the probability distribution of size four for each token in the sequence. As per the definition, the greedy decoder generates the sequence with the highest probability by choosing the most probable tokens at each time step.
Beam search decoding is another popular way of decoding model predictions that leads to better results than the greedy search decoder in almost all cases. Unlike greedy decoder, it doesn’t just consider the most probable token at each prediction, it considers top-k tokens having higher probabilities (where k is called the beam-width or beam-size). Although beam-search gives better results, it makes the overall pipeline slow as it is computationally complex.
Thus it doesn’t just give you one output sequence, it gives you k-different output sequences along with their likelihood (probabilities). Unlike greedy decoder where we had only a single output sequence, we have k different output sequences here and there is a very good chance that one of these k sequences is the correct output sequence.
For the first time-step prediction, choose k tokens having higher probabilities instead of one (as in greedy we choose only one). Now going further, consider every token of the current prediction and append it to all the previously decoded k sequences and keep calculating corresponding probabilities of new sequences. Now choose top k sequences out of the new sequences based on the probability score and move to the next time-step. Repeat this process until the last token. Finally, return k sequences with their corresponding probability values.
Tip: word-beam-search is another variant of beam-search decoding technique that restricts to or chooses output sequences having dictionary words only. It performs better than a vanilla beam search in most cases.
Writing a beam search decoder in Python—
It’s because a regular probability would cause problems when there are longer sequences. For example — Consider a sequence of length 100 is generated by the model. And the probability of each token in the sequence is 0.10 then the probability of the output sequence would be the multiplication of all these probabilities —
Probability of a sequence with 100 tokens would be--P(sequence) = p(t1) * p(t2) * p(t3) .............. * p(t100) = 0.1 * 0.1 * 0.1 * .................... * 0.1 = 10 ^ (-100) # An extremely small number
As we can see it’s an extremely small number. Any programing language might fail to compare such small floating-point numbers as this could cause under-flow. This is why we calculate log-probabilities instead of regular probability. If you pay attention we are multiplying negative log-probability to calculate the score (line 16 in code), this is because the logarithm of a probability ( 0 < 1.0) is always a negative number. And thus we are choosing the top k sequences with minimum log-scores.
Probability of sequence with N tokens would be —
P(seq) = p(t1) * p(t2) * p(t3) ........ p(tN)### taking log on both sides (calculate log-likelihood)log(P(seq)) = log(p(t1) * p(t2) * p(t3) ........ p(tN)) log(P(seq)) = log(p(t1)) + log(p(t2)) + .. log(p(tN))### logarithm of a number < 1.0 will be always negative so in this ### case log-likelihood of the sequence would be negative.
If we take a log on both sides, this multiplication will convert to a summation. Hence calculation of the log-likelihood instead of real probability would be faster and efficient. As we know logarithm of a number < 1.0 would always be a negative number. So we will get a negative score for our sequence. We can convert this score(log-likelihood) to the original probability by taking the anti-logarithm of this score. For the purpose of finding k best sequences using the beam-search, we only need to compare the probabilities of certain sequences, so the log-likelihood would work just fine.
Now we know that the beam search decoder gives you k different output sequences instead of one and there are good chances that one of these sequences is the correct output. But we don’t have a way to identify which of the output sequence is the best. This is where a language model comes into the picture.
A language model is a statistical representation of a given language. It is supposed to be able to guess the next word if a list of previously occurring words is given, from a given sentence. In other words, A language model is something that can determine the probability of a given text-sequence (sentence) where sequence tokens (chars/words) are pulled from a fixed vocabulary (language vocab). So, basically it can score your sentence. A good score means that the sentence is contextually correct and belongs to the given language.
Language models are usually trained on a very large corpus of the text and are able to understand(learn) the context(co-occurrence) of words in the given sentences. A language model not necessarily has to be word-level, we can train the language model on characters as well. A character-level language model is supposed to guess the next character in a sequence, given the previous few characters. Again character-level models can also give you the probability (or likelihood) of a given sentence.
Consider a scenario where a deep learning model is trying to generate some text (or consider a problem where the model is trying to convert voice to text) and the resulting probability distribution of characters is sent to the beam search decoder with a beam-width of 5. Assume that the following are the top 5 sequences generated using beam-search-decoding.
Generated Sequences Probability (model)1. speech recogniiion is a hald problem 0.412. speech recog niiion isa hard problem 0.393. speech recognition is a hard problem 0.374. spe ech recogniion is a hard problem 0.325. spe ech recogni tion is ahard problem 0.29
A greedy-search-decoder will give you the first sequence as output because it is the sequence with the highest probability (0.41) as per our model. But clearly (3) is the correct output with slightly lesser probability.
To find the best sequence out of these 5 sequences, we will use the language model to check the likelihood of each of these sequences as per the English language. If our language model is well trained, it is supposed to give a good probability(score) to the third sequence as it is 100% correct as per the English language.
Assuming that the following are the likelihoods of these 5 sequences as per our language model.
Generated Sequences Probability Probability (model) (L.M.)1. speech recogniiion is a hald problem 0.41 0.202. speech recog niiion isa hard problem 0.39 0.403. speech recognition is a hard problem 0.37 0.704. spe ech recogniion is a hard problem 0.32 0.355. spe ech recogni tion is ahard problem 0.29 0.47
Now to choose the best output sequence, we will consider the weighted sum of both the probabilities —
P(final) = Alpha * P(model) + Beta * P(L.M.)
Values of the constants Alpha and Beta is decided after tuning them on the validation dataset. We choose the values which give the best result on the validation set. We then use those values to evaluate our model on the test set.
*Note: Sometimes the sequence length is also considered while calculating the final score of a sequence. If we don’t penalize the scores with the sequence lengths, our model will give more preference to the smaller sequences. As the score would be lesser for the longer sequences (multiplication of more probability values (p < 1.0) will result in even smaller scores).
Tip: It is observed that using a word-level language model gives better results in most cases. To be able to use a word-level language model for scoring, output sequences should be restricted to the dictionary words only. Thus a word-beam-search algorithm is used to come up with restricted beams and later those beams are re-scored with the language model to decide the final output.
PS: Usually, as per research-papers, a very large number is used as beam-size (~1000–2000) is used while applying beam-search. It delivers better results but at the cost of speed as inference becomes quite slow.
Originally published here.
Few research papers utilizing beam-search decoding and a language model to improve the results —
https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdfListen, Attend and Spell (https://arxiv.org/pdf/1508.01211.pdf)Show and Tell (https://arxiv.org/pdf/1411.4555.pdf)SEQUENCER (https://arxiv.org/pdf/1901.01808.pdf)
https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf
Listen, Attend and Spell (https://arxiv.org/pdf/1508.01211.pdf)
Show and Tell (https://arxiv.org/pdf/1411.4555.pdf)
SEQUENCER (https://arxiv.org/pdf/1901.01808.pdf)
(matrix image) https://www.shutterstock.com/image-vector/digital-binary-code-matrix-backgrounddata-flood-1341680024(LSTM autoencoder) https://stackoverflow.com/questions/45977990/tensorflow-how-to-embed-float-sequences-to-fixed-size-vectors
(matrix image) https://www.shutterstock.com/image-vector/digital-binary-code-matrix-backgrounddata-flood-1341680024
(LSTM autoencoder) https://stackoverflow.com/questions/45977990/tensorflow-how-to-embed-float-sequences-to-fixed-size-vectors
That’ll be all !
Thanks for reading, Don‘t forget to share your thoughts with me. | [
{
"code": null,
"e": 676,
"s": 172,
"text": "Whenever Image Processing, Audio data Analysis or Natural language processing (NLP) tasks are concerned, Deep learning has proved to be an ideal choice and has shown outstanding outcomes. Neural Network-based model architectures are really good at understanding complex patterns as well as generating meaningful and realistic data. Although deep learning-based solutions are generally very efficient, it’s never a bad idea to use better post-processing techniques to make predictions even more accurate."
},
{
"code": null,
"e": 1262,
"s": 676,
"text": "Complex problems such as Neural Machine Translation (NMT), Image caption generation (ICG) and speech recognition (ASR) are very much solvable today using deep learning. These problems are categorized as sequence generation problems where given an input, the model learns to generate some text sequence. If you take a look at the research papers showing state of the art (SOTA) results on these tasks, you will probably find their solution utilizing a beam search decoder fused with a Language model to boost the results. Let’s learn more about these decoding techniques with examples —"
},
{
"code": null,
"e": 1537,
"s": 1262,
"text": "Going further, we will define an example sequence generation problem and explore post-processing (decoding) techniques. We will start with a greedy-search-decoding technique and introduce beam-search-decoding fused with language model to further improve the overall results."
},
{
"code": null,
"e": 1988,
"s": 1537,
"text": "Consider a problem of English language text generation and suppose we have already trained a model to do that. Depending upon the nature of the problem or solution strategy, our model might be a character-level model or a word-level model. A character-level text generator model generates text by predicting one character at a time. Similarly, a word-level text generator predicts one word at a time and multiple predicted such words make a sequence."
},
{
"code": null,
"e": 2595,
"s": 1988,
"text": "Assume we have trained a character-level model that generates text by predicting one character at a time. This problem can be related to any of the following problems — Speech to Text, Optical Character Recognition, Image caption generation....etc. Such problems are usually solved using an encoder-decoder architecture as shown in the figure below. The encoder part is responsible for taking an input vector (audio, image or text....) and producing an encoded context vector. The decoder part then uses that context vector to generate the output sequence by predicting one token (char/ wordbbb) at a time."
},
{
"code": null,
"e": 2990,
"s": 2595,
"text": "As our model is character-level, It will generate a probability distribution over all the possible characters for each token in the output sequence. In other words — For each token (char) our model is predicting, it will generate a probability array of length 26 (as per the English language — a to z) and the probabilities will show how likely a particular character is to be the output token."
},
{
"code": null,
"e": 3089,
"s": 2990,
"text": "For a predicted sequence of length 10 (chars), our models' output would look something like this —"
},
{
"code": null,
"e": 3398,
"s": 3089,
"text": "output_shape = 10 * 26 output = [[0.1, 0.01, 0.03, ... ... ... ... ... (len-26)], [0.1, 0.002, 0.6, ... ... ... ... ... (len-26)], '' '' '' '' '' '' '' '' '' '' [0.9, 0.01, 0.01, ... ... ... ... ... (len-26)]]"
},
{
"code": null,
"e": 3647,
"s": 3398,
"text": "To convert this probabilistic output into a readable form (English text), we need a decoding algorithm. The simplest decoder would be a greedy-search-decoder. Let’s write a greedy-search-decoder along with a complex one called beam-search-decoder —"
},
{
"code": null,
"e": 3892,
"s": 3647,
"text": "Note — A sequence generation problem doesn’t necessarily involve text generation, it could be any kind of sequence. We are taking a text generation problem as an example because we are going to talk about language modeling as well in this post."
},
{
"code": null,
"e": 4319,
"s": 3892,
"text": "The simplest way to decode the models’ predictions is to consider the most likely sequence as output. A greedy decoder, also called as the best-path decoder considers the token (character or word) with the highest probability in each prediction and concatenates all the predicted tokens to get the final output sequence. This is a simple and fast way to get the output sequence. But it may not always give you the best output."
},
{
"code": null,
"e": 4385,
"s": 4319,
"text": "Here is how you write a greedy decoder for your model in Python —"
},
{
"code": null,
"e": 4806,
"s": 4385,
"text": "Here the shape of the model's prediction is 5*4 that means, the model is trying to generate a sequence of length five. As there are only four different tokens in the vocabulary, the model predicts the probability distribution of size four for each token in the sequence. As per the definition, the greedy decoder generates the sequence with the highest probability by choosing the most probable tokens at each time step."
},
{
"code": null,
"e": 5268,
"s": 4806,
"text": "Beam search decoding is another popular way of decoding model predictions that leads to better results than the greedy search decoder in almost all cases. Unlike greedy decoder, it doesn’t just consider the most probable token at each prediction, it considers top-k tokens having higher probabilities (where k is called the beam-width or beam-size). Although beam-search gives better results, it makes the overall pipeline slow as it is computationally complex."
},
{
"code": null,
"e": 5608,
"s": 5268,
"text": "Thus it doesn’t just give you one output sequence, it gives you k-different output sequences along with their likelihood (probabilities). Unlike greedy decoder where we had only a single output sequence, we have k different output sequences here and there is a very good chance that one of these k sequences is the correct output sequence."
},
{
"code": null,
"e": 6157,
"s": 5608,
"text": "For the first time-step prediction, choose k tokens having higher probabilities instead of one (as in greedy we choose only one). Now going further, consider every token of the current prediction and append it to all the previously decoded k sequences and keep calculating corresponding probabilities of new sequences. Now choose top k sequences out of the new sequences based on the probability score and move to the next time-step. Repeat this process until the last token. Finally, return k sequences with their corresponding probability values."
},
{
"code": null,
"e": 6369,
"s": 6157,
"text": "Tip: word-beam-search is another variant of beam-search decoding technique that restricts to or chooses output sequences having dictionary words only. It performs better than a vanilla beam search in most cases."
},
{
"code": null,
"e": 6410,
"s": 6369,
"text": "Writing a beam search decoder in Python—"
},
{
"code": null,
"e": 6733,
"s": 6410,
"text": "It’s because a regular probability would cause problems when there are longer sequences. For example — Consider a sequence of length 100 is generated by the model. And the probability of each token in the sequence is 0.10 then the probability of the output sequence would be the multiplication of all these probabilities —"
},
{
"code": null,
"e": 6958,
"s": 6733,
"text": "Probability of a sequence with 100 tokens would be--P(sequence) = p(t1) * p(t2) * p(t3) .............. * p(t100) = 0.1 * 0.1 * 0.1 * .................... * 0.1 = 10 ^ (-100) # An extremely small number "
},
{
"code": null,
"e": 7455,
"s": 6958,
"text": "As we can see it’s an extremely small number. Any programing language might fail to compare such small floating-point numbers as this could cause under-flow. This is why we calculate log-probabilities instead of regular probability. If you pay attention we are multiplying negative log-probability to calculate the score (line 16 in code), this is because the logarithm of a probability ( 0 < 1.0) is always a negative number. And thus we are choosing the top k sequences with minimum log-scores."
},
{
"code": null,
"e": 7504,
"s": 7455,
"text": "Probability of sequence with N tokens would be —"
},
{
"code": null,
"e": 7842,
"s": 7504,
"text": "P(seq) = p(t1) * p(t2) * p(t3) ........ p(tN)### taking log on both sides (calculate log-likelihood)log(P(seq)) = log(p(t1) * p(t2) * p(t3) ........ p(tN)) log(P(seq)) = log(p(t1)) + log(p(t2)) + .. log(p(tN))### logarithm of a number < 1.0 will be always negative so in this ### case log-likelihood of the sequence would be negative."
},
{
"code": null,
"e": 8435,
"s": 7842,
"text": "If we take a log on both sides, this multiplication will convert to a summation. Hence calculation of the log-likelihood instead of real probability would be faster and efficient. As we know logarithm of a number < 1.0 would always be a negative number. So we will get a negative score for our sequence. We can convert this score(log-likelihood) to the original probability by taking the anti-logarithm of this score. For the purpose of finding k best sequences using the beam-search, we only need to compare the probabilities of certain sequences, so the log-likelihood would work just fine."
},
{
"code": null,
"e": 8741,
"s": 8435,
"text": "Now we know that the beam search decoder gives you k different output sequences instead of one and there are good chances that one of these sequences is the correct output. But we don’t have a way to identify which of the output sequence is the best. This is where a language model comes into the picture."
},
{
"code": null,
"e": 9277,
"s": 8741,
"text": "A language model is a statistical representation of a given language. It is supposed to be able to guess the next word if a list of previously occurring words is given, from a given sentence. In other words, A language model is something that can determine the probability of a given text-sequence (sentence) where sequence tokens (chars/words) are pulled from a fixed vocabulary (language vocab). So, basically it can score your sentence. A good score means that the sentence is contextually correct and belongs to the given language."
},
{
"code": null,
"e": 9775,
"s": 9277,
"text": "Language models are usually trained on a very large corpus of the text and are able to understand(learn) the context(co-occurrence) of words in the given sentences. A language model not necessarily has to be word-level, we can train the language model on characters as well. A character-level language model is supposed to guess the next character in a sequence, given the previous few characters. Again character-level models can also give you the probability (or likelihood) of a given sentence."
},
{
"code": null,
"e": 10134,
"s": 9775,
"text": "Consider a scenario where a deep learning model is trying to generate some text (or consider a problem where the model is trying to convert voice to text) and the resulting probability distribution of characters is sent to the beam search decoder with a beam-width of 5. Assume that the following are the top 5 sequences generated using beam-search-decoding."
},
{
"code": null,
"e": 10473,
"s": 10134,
"text": "Generated Sequences Probability (model)1. speech recogniiion is a hald problem 0.412. speech recog niiion isa hard problem 0.393. speech recognition is a hard problem 0.374. spe ech recogniion is a hard problem 0.325. spe ech recogni tion is ahard problem 0.29"
},
{
"code": null,
"e": 10693,
"s": 10473,
"text": "A greedy-search-decoder will give you the first sequence as output because it is the sequence with the highest probability (0.41) as per our model. But clearly (3) is the correct output with slightly lesser probability."
},
{
"code": null,
"e": 11017,
"s": 10693,
"text": "To find the best sequence out of these 5 sequences, we will use the language model to check the likelihood of each of these sequences as per the English language. If our language model is well trained, it is supposed to give a good probability(score) to the third sequence as it is 100% correct as per the English language."
},
{
"code": null,
"e": 11113,
"s": 11017,
"text": "Assuming that the following are the likelihoods of these 5 sequences as per our language model."
},
{
"code": null,
"e": 11567,
"s": 11113,
"text": "Generated Sequences Probability Probability (model) (L.M.)1. speech recogniiion is a hald problem 0.41 0.202. speech recog niiion isa hard problem 0.39 0.403. speech recognition is a hard problem 0.37 0.704. spe ech recogniion is a hard problem 0.32 0.355. spe ech recogni tion is ahard problem 0.29 0.47"
},
{
"code": null,
"e": 11669,
"s": 11567,
"text": "Now to choose the best output sequence, we will consider the weighted sum of both the probabilities —"
},
{
"code": null,
"e": 11726,
"s": 11669,
"text": " P(final) = Alpha * P(model) + Beta * P(L.M.)"
},
{
"code": null,
"e": 11956,
"s": 11726,
"text": "Values of the constants Alpha and Beta is decided after tuning them on the validation dataset. We choose the values which give the best result on the validation set. We then use those values to evaluate our model on the test set."
},
{
"code": null,
"e": 12326,
"s": 11956,
"text": "*Note: Sometimes the sequence length is also considered while calculating the final score of a sequence. If we don’t penalize the scores with the sequence lengths, our model will give more preference to the smaller sequences. As the score would be lesser for the longer sequences (multiplication of more probability values (p < 1.0) will result in even smaller scores)."
},
{
"code": null,
"e": 12711,
"s": 12326,
"text": "Tip: It is observed that using a word-level language model gives better results in most cases. To be able to use a word-level language model for scoring, output sequences should be restricted to the dictionary words only. Thus a word-beam-search algorithm is used to come up with restricted beams and later those beams are re-scored with the language model to decide the final output."
},
{
"code": null,
"e": 12923,
"s": 12711,
"text": "PS: Usually, as per research-papers, a very large number is used as beam-size (~1000–2000) is used while applying beam-search. It delivers better results but at the cost of speed as inference becomes quite slow."
},
{
"code": null,
"e": 12950,
"s": 12923,
"text": "Originally published here."
},
{
"code": null,
"e": 13047,
"s": 12950,
"text": "Few research papers utilizing beam-search decoding and a language model to improve the results —"
},
{
"code": null,
"e": 13298,
"s": 13047,
"text": "https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdfListen, Attend and Spell (https://arxiv.org/pdf/1508.01211.pdf)Show and Tell (https://arxiv.org/pdf/1411.4555.pdf)SEQUENCER (https://arxiv.org/pdf/1901.01808.pdf)"
},
{
"code": null,
"e": 13387,
"s": 13298,
"text": "https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf"
},
{
"code": null,
"e": 13451,
"s": 13387,
"text": "Listen, Attend and Spell (https://arxiv.org/pdf/1508.01211.pdf)"
},
{
"code": null,
"e": 13503,
"s": 13451,
"text": "Show and Tell (https://arxiv.org/pdf/1411.4555.pdf)"
},
{
"code": null,
"e": 13552,
"s": 13503,
"text": "SEQUENCER (https://arxiv.org/pdf/1901.01808.pdf)"
},
{
"code": null,
"e": 13793,
"s": 13552,
"text": "(matrix image) https://www.shutterstock.com/image-vector/digital-binary-code-matrix-backgrounddata-flood-1341680024(LSTM autoencoder) https://stackoverflow.com/questions/45977990/tensorflow-how-to-embed-float-sequences-to-fixed-size-vectors"
},
{
"code": null,
"e": 13909,
"s": 13793,
"text": "(matrix image) https://www.shutterstock.com/image-vector/digital-binary-code-matrix-backgrounddata-flood-1341680024"
},
{
"code": null,
"e": 14035,
"s": 13909,
"text": "(LSTM autoencoder) https://stackoverflow.com/questions/45977990/tensorflow-how-to-embed-float-sequences-to-fixed-size-vectors"
},
{
"code": null,
"e": 14052,
"s": 14035,
"text": "That’ll be all !"
}
]
|
Create a Crypto Currency Price Tracking Chrome Extension - GeeksforGeeks | 28 Mar, 2021
Building a Chrome extension requires you to have a knowledge of HTML, CSS, JavaScript, and Bootstrap. In this article, we will be making an extension that tracks the prices of various cryptocurrencies. For fetching the data regarding the prices of cryptocurrencies, we will be using an API known as CryptoCompare.
What is an API?
API stands for application programming interface. Basically, it is a messenger that takes a request from us and return a response accordingly. An API also has something known as endpoints. An endpoint is a URL that allows an API to gain access to some part of the server and retrieve data accordingly. An API returns data in the form of JSON (JavaScript Object Notation) which is in the form of key-value pairs.
Let’s start building the Crypto Currency Price Tracker!!!
Building the User Interface-
First, we will be creating two files with the name popup.html and popup.js (why we have named them popup will be clear later. Now inside the popup.html, we will be creating the basic UI of our extension. First add the basic boilerplate code of HTML than in the body section add the code as shown below:-
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!--Add Bootstrap CDN link here--> <title>CryptoCount</title> <style> html, body { font-family: "Open Sans", sans-serif; font-size: 14px; margin: 0; min-height: 600px; padding: 0; width: 500px; } </style></head> <body> <div class="container"> <h2 class="text-center">CryptoCount</h2> <div class="text-right pb-4"> <select id="select1"> <option value="INR">INR</option> <option value="USD">USD</option> <option value="EUR">EUR</option> <option value="BTC">BTC</option> </select> <button class="btn btn-dark changeData"> Fetch Data </button> </div> <table class="table table-striped table-dark data-back"> </table> </div> <script src="popup.js"></script></body> </html>
This code will add the title CryptoCount ( this is what we named it, you can name as you wish) and a dropdown list which contains 4 options to change the currency of the data which we will be fetching from CryptoCompare API. A button is added which will bring data from the API, and we will be adding the brought data dynamically using JavaScript to the table element.
Adding some JavaScript –
In our popup.js file we will be adding an IFFE function basically this function is invoked as soon the DOM is loaded. The API that we will be using to get data is:- https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=INR&api_key={your_API_KEY goes here}. This IFFI function will render the data you can check by doing a console.log(response).
Javascript
document.querySelector(".changeData") .addEventListener("click", changeData); const getDataAndRender = (function getData(currency = "INR") { const xhr = new XMLHttpRequest(); const url = "min-api.cryptocompare.com/data/top/totalvolfull"; xhr.open("GET", `https://{url}?limit=10&tsym=${currency}&api_key={API_KEY}`, true); let output = "<tr> <td> <b></b> </td> <td> <b>Coin</b> </td> <td> <b>PRICE</b> </td> <td> <b>HIGH DAY</b> </td> <td> <b>LOW DAY</b> </td> </tr>"; xhr.onload = function () { if (this.status === 200) { const response = JSON.parse(this.responseText); const dataArr = response.Data; dataArr.forEach(function (data) { const name = data.CoinInfo.FullName; const imgURL = data.CoinInfo.ImageUrl; const price = data.DISPLAY.INR.PRICE; console.log(typeof data.CoinInfo.FullName); const img = `https://www.cryptocompare.com/${imgURL}`; const highDay = data.DISPLAY.INR.HIGHDAY; const lowDay = data.DISPLAY.INR.LOWDAY; output += ` <tr><td><img src=${img} width="30" height="30"></td> <td>${name}</td> <td>${price}</td> <td>${highDay}</td> <td>${lowDay}</td></tr>` }) document.querySelector( ".data-back").innerHTML = output; }}xhr.send(); }) ();
Now as we have logged the data into the console, and we can see that we are successfully able to fetch data from the API. Now it’s time to reflect this data into the UI of our extension. For that, we will be selecting the DOM element with the class name of data-back. Now we will be inserting the output variable that contains<td></td> element with parameters like image, name, price (You can get tons of information from the API but for the sake of simplicity we will be just using image URL, name, price of the coin). Now add this to the DOM using the line of code as – document.querySelector(“.data-back”).innerHTML=output;
This is what our UI will be looking like –
UI
Now we will be implementing the functionality to change the type of currency dynamically. For implementing this we will get the value of the field present in the drop-down list. By default, the type of currency would be rupee. For getting the type of currency present in the dropdown list we will be making a function named getCurrency().
Javascript
function getCurrency() { const selectElement =document.querySelector('#select1'); const output = selectElement.value; // console.log("get" ,output); return output;}
When someone selects the type of currency, getCurrency method will return whether it is “INR”, “USD”, “BTC” or “EUR”. Now we will make a new API call by changing the endpoint from INR(default endpoint) to the value selected from the list.
Javascript
function changeData(){ const newOutput=getCurrency(); console.log(newOutput); document.querySelector(".data-back").innerHTML=""; getDataNew(newOutput);}
The button Fetch’s the data when clicked and will trigger the method changeData , which will first clear the contents already present in the DOM and will insert a new table element with a new currency type into the DOM and also it will further call two functions one will tell the type of currency and other will do insertion of a new table with changed currency type into the DOM. The implementation of the function getDataNew is the same as that of getData function discussed above. The development part of this CryptoCurrency Price Tracker is over. Now we will be making a chrome extension out of it.
Making a Chrome extension – For making a Chrome extension we will need a manifest.json file and the creation of this file is as shown below –
Javascript
{ "manifest_version":2, "name":"CryptoCount", "description":"CryptoCount tells you the current price of top cryptocurrencies", "version":"1.0.0", "icons":{"128":"favicon.png"}, "browser_action":{ "default_icon":"favicon.png", "default_popup":"popup.html" }, "permissions":["activeTab"]}
This is the way to create the manifest file as per the documentation of https://developer.chrome.com/extensions/manifest. Add place this file along with the popup.html, popup.js into a folder. We named them popup.js and popup.html as per documentation. Create a folder called images and place the image that you would like to be shown in the Chrome extension bar of Google Chrome.
Now there are two ways to upload to chrome store –
1. One way is by paying a $5 fee and creating a developer account.
2. The other is a free way of uploading to chrome store which is as follows –
In the URL of your Chrome browser type chrome://extensions/
Now turn on the developer mode.
Now click on the button in the top left corner saying Load Unpacked.
A popup bar will appear and will ask you to upload the files created above.
Upload the files and you are good to go
This is what you will see once you are done uploading the files. Now go to the Chrome extension bar and you will be able to see your own Chrome extension and will be able to access it.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Chrome
Web-API
Bootstrap
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to keep gap between columns using Bootstrap?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 25205,
"s": 25177,
"text": "\n28 Mar, 2021"
},
{
"code": null,
"e": 25520,
"s": 25205,
"text": "Building a Chrome extension requires you to have a knowledge of HTML, CSS, JavaScript, and Bootstrap. In this article, we will be making an extension that tracks the prices of various cryptocurrencies. For fetching the data regarding the prices of cryptocurrencies, we will be using an API known as CryptoCompare. "
},
{
"code": null,
"e": 25536,
"s": 25520,
"text": "What is an API?"
},
{
"code": null,
"e": 25948,
"s": 25536,
"text": "API stands for application programming interface. Basically, it is a messenger that takes a request from us and return a response accordingly. An API also has something known as endpoints. An endpoint is a URL that allows an API to gain access to some part of the server and retrieve data accordingly. An API returns data in the form of JSON (JavaScript Object Notation) which is in the form of key-value pairs."
},
{
"code": null,
"e": 26006,
"s": 25948,
"text": "Let’s start building the Crypto Currency Price Tracker!!!"
},
{
"code": null,
"e": 26035,
"s": 26006,
"text": "Building the User Interface-"
},
{
"code": null,
"e": 26340,
"s": 26035,
"text": "First, we will be creating two files with the name popup.html and popup.js (why we have named them popup will be clear later. Now inside the popup.html, we will be creating the basic UI of our extension. First add the basic boilerplate code of HTML than in the body section add the code as shown below:- "
},
{
"code": null,
"e": 26345,
"s": 26340,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!--Add Bootstrap CDN link here--> <title>CryptoCount</title> <style> html, body { font-family: \"Open Sans\", sans-serif; font-size: 14px; margin: 0; min-height: 600px; padding: 0; width: 500px; } </style></head> <body> <div class=\"container\"> <h2 class=\"text-center\">CryptoCount</h2> <div class=\"text-right pb-4\"> <select id=\"select1\"> <option value=\"INR\">INR</option> <option value=\"USD\">USD</option> <option value=\"EUR\">EUR</option> <option value=\"BTC\">BTC</option> </select> <button class=\"btn btn-dark changeData\"> Fetch Data </button> </div> <table class=\"table table-striped table-dark data-back\"> </table> </div> <script src=\"popup.js\"></script></body> </html>",
"e": 27444,
"s": 26345,
"text": null
},
{
"code": null,
"e": 27813,
"s": 27444,
"text": "This code will add the title CryptoCount ( this is what we named it, you can name as you wish) and a dropdown list which contains 4 options to change the currency of the data which we will be fetching from CryptoCompare API. A button is added which will bring data from the API, and we will be adding the brought data dynamically using JavaScript to the table element."
},
{
"code": null,
"e": 27838,
"s": 27813,
"text": "Adding some JavaScript –"
},
{
"code": null,
"e": 28200,
"s": 27838,
"text": "In our popup.js file we will be adding an IFFE function basically this function is invoked as soon the DOM is loaded. The API that we will be using to get data is:- https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=INR&api_key={your_API_KEY goes here}. This IFFI function will render the data you can check by doing a console.log(response)."
},
{
"code": null,
"e": 28211,
"s": 28200,
"text": "Javascript"
},
{
"code": "document.querySelector(\".changeData\") .addEventListener(\"click\", changeData); const getDataAndRender = (function getData(currency = \"INR\") { const xhr = new XMLHttpRequest(); const url = \"min-api.cryptocompare.com/data/top/totalvolfull\"; xhr.open(\"GET\", `https://{url}?limit=10&tsym=${currency}&api_key={API_KEY}`, true); let output = \"<tr> <td> <b></b> </td> <td> <b>Coin</b> </td> <td> <b>PRICE</b> </td> <td> <b>HIGH DAY</b> </td> <td> <b>LOW DAY</b> </td> </tr>\"; xhr.onload = function () { if (this.status === 200) { const response = JSON.parse(this.responseText); const dataArr = response.Data; dataArr.forEach(function (data) { const name = data.CoinInfo.FullName; const imgURL = data.CoinInfo.ImageUrl; const price = data.DISPLAY.INR.PRICE; console.log(typeof data.CoinInfo.FullName); const img = `https://www.cryptocompare.com/${imgURL}`; const highDay = data.DISPLAY.INR.HIGHDAY; const lowDay = data.DISPLAY.INR.LOWDAY; output += ` <tr><td><img src=${img} width=\"30\" height=\"30\"></td> <td>${name}</td> <td>${price}</td> <td>${highDay}</td> <td>${lowDay}</td></tr>` }) document.querySelector( \".data-back\").innerHTML = output; }}xhr.send(); }) ();",
"e": 29802,
"s": 28211,
"text": null
},
{
"code": null,
"e": 30432,
"s": 29804,
"text": "Now as we have logged the data into the console, and we can see that we are successfully able to fetch data from the API. Now it’s time to reflect this data into the UI of our extension. For that, we will be selecting the DOM element with the class name of data-back. Now we will be inserting the output variable that contains<td></td> element with parameters like image, name, price (You can get tons of information from the API but for the sake of simplicity we will be just using image URL, name, price of the coin). Now add this to the DOM using the line of code as – document.querySelector(“.data-back”).innerHTML=output; "
},
{
"code": null,
"e": 30475,
"s": 30432,
"text": "This is what our UI will be looking like –"
},
{
"code": null,
"e": 30479,
"s": 30475,
"text": "UI "
},
{
"code": null,
"e": 30818,
"s": 30479,
"text": "Now we will be implementing the functionality to change the type of currency dynamically. For implementing this we will get the value of the field present in the drop-down list. By default, the type of currency would be rupee. For getting the type of currency present in the dropdown list we will be making a function named getCurrency()."
},
{
"code": null,
"e": 30829,
"s": 30818,
"text": "Javascript"
},
{
"code": "function getCurrency() { const selectElement =document.querySelector('#select1'); const output = selectElement.value; // console.log(\"get\" ,output); return output;}",
"e": 31030,
"s": 30829,
"text": null
},
{
"code": null,
"e": 31269,
"s": 31030,
"text": "When someone selects the type of currency, getCurrency method will return whether it is “INR”, “USD”, “BTC” or “EUR”. Now we will make a new API call by changing the endpoint from INR(default endpoint) to the value selected from the list."
},
{
"code": null,
"e": 31280,
"s": 31269,
"text": "Javascript"
},
{
"code": "function changeData(){ const newOutput=getCurrency(); console.log(newOutput); document.querySelector(\".data-back\").innerHTML=\"\"; getDataNew(newOutput);}",
"e": 31453,
"s": 31280,
"text": null
},
{
"code": null,
"e": 32058,
"s": 31453,
"text": "The button Fetch’s the data when clicked and will trigger the method changeData , which will first clear the contents already present in the DOM and will insert a new table element with a new currency type into the DOM and also it will further call two functions one will tell the type of currency and other will do insertion of a new table with changed currency type into the DOM. The implementation of the function getDataNew is the same as that of getData function discussed above. The development part of this CryptoCurrency Price Tracker is over. Now we will be making a chrome extension out of it."
},
{
"code": null,
"e": 32200,
"s": 32058,
"text": "Making a Chrome extension – For making a Chrome extension we will need a manifest.json file and the creation of this file is as shown below –"
},
{
"code": null,
"e": 32211,
"s": 32200,
"text": "Javascript"
},
{
"code": "{ \"manifest_version\":2, \"name\":\"CryptoCount\", \"description\":\"CryptoCount tells you the current price of top cryptocurrencies\", \"version\":\"1.0.0\", \"icons\":{\"128\":\"favicon.png\"}, \"browser_action\":{ \"default_icon\":\"favicon.png\", \"default_popup\":\"popup.html\" }, \"permissions\":[\"activeTab\"]}",
"e": 32544,
"s": 32211,
"text": null
},
{
"code": null,
"e": 32926,
"s": 32544,
"text": "This is the way to create the manifest file as per the documentation of https://developer.chrome.com/extensions/manifest. Add place this file along with the popup.html, popup.js into a folder. We named them popup.js and popup.html as per documentation. Create a folder called images and place the image that you would like to be shown in the Chrome extension bar of Google Chrome."
},
{
"code": null,
"e": 32977,
"s": 32926,
"text": "Now there are two ways to upload to chrome store –"
},
{
"code": null,
"e": 33044,
"s": 32977,
"text": "1. One way is by paying a $5 fee and creating a developer account."
},
{
"code": null,
"e": 33122,
"s": 33044,
"text": "2. The other is a free way of uploading to chrome store which is as follows –"
},
{
"code": null,
"e": 33182,
"s": 33122,
"text": "In the URL of your Chrome browser type chrome://extensions/"
},
{
"code": null,
"e": 33214,
"s": 33182,
"text": "Now turn on the developer mode."
},
{
"code": null,
"e": 33283,
"s": 33214,
"text": "Now click on the button in the top left corner saying Load Unpacked."
},
{
"code": null,
"e": 33359,
"s": 33283,
"text": "A popup bar will appear and will ask you to upload the files created above."
},
{
"code": null,
"e": 33399,
"s": 33359,
"text": "Upload the files and you are good to go"
},
{
"code": null,
"e": 33584,
"s": 33399,
"text": "This is what you will see once you are done uploading the files. Now go to the Chrome extension bar and you will be able to see your own Chrome extension and will be able to access it."
},
{
"code": null,
"e": 33721,
"s": 33584,
"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": 33728,
"s": 33721,
"text": "Chrome"
},
{
"code": null,
"e": 33736,
"s": 33728,
"text": "Web-API"
},
{
"code": null,
"e": 33746,
"s": 33736,
"text": "Bootstrap"
},
{
"code": null,
"e": 33750,
"s": 33746,
"text": "CSS"
},
{
"code": null,
"e": 33755,
"s": 33750,
"text": "HTML"
},
{
"code": null,
"e": 33772,
"s": 33755,
"text": "Web Technologies"
},
{
"code": null,
"e": 33777,
"s": 33772,
"text": "HTML"
},
{
"code": null,
"e": 33875,
"s": 33777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33884,
"s": 33875,
"text": "Comments"
},
{
"code": null,
"e": 33897,
"s": 33884,
"text": "Old Comments"
},
{
"code": null,
"e": 33938,
"s": 33897,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 34001,
"s": 33938,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 34034,
"s": 34001,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 34060,
"s": 34034,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 34109,
"s": 34060,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 34171,
"s": 34109,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34221,
"s": 34171,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34279,
"s": 34221,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 34327,
"s": 34279,
"text": "How to update Node.js and NPM to next version ?"
}
]
|
Set user variable from result of query in MySQL? | To set user variable from result of query in MySQL, you need to move that variable into the assignment.
To understand the above concept, let us first create a table. The query to create a table is as follows −
mysql> create table UserVariable
-> (
-> Id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into UserVariable values(101,'John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into UserVariable values(200,'Tom');
Query OK, 1 row affected (0.18 sec)
mysql> insert into UserVariable values(500,'Carol');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from UserVariable;
+------+-------+
| Id | Name |
+------+-------+
| 101 | John |
| 200 | Tom |
| 500 | Carol |
+------+-------+
3 rows in set (0.00 sec)
Write a query with a user variable that display the records with maximum id. First, I am going to create a variable and initialize this variable by selecting maximum id from the above table. The query is as follows −
mysql> set @Maxid=(select MAX(Id) from UserVariable);
Query OK, 0 rows affected (0.00 sec)
After that, create another variable which has only name with that particular maximum id. The query is as follows −
mysql> set @Name=(select Name from UserVariable where Id=@Maxid);
Query OK, 0 rows affected (0.00 sec)
Now you can check what value is present in variable Name. The query is as follows −
mysql> select @Name;
The following is the output that displays the name with the highest Id −
+-------+
| @Name |
+-------+
| Carol |
+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "To set user variable from result of query in MySQL, you need to move that variable into the assignment."
},
{
"code": null,
"e": 1272,
"s": 1166,
"text": "To understand the above concept, let us first create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1397,
"s": 1272,
"text": "mysql> create table UserVariable\n -> (\n -> Id int,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1478,
"s": 1397,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 1744,
"s": 1478,
"text": "mysql> insert into UserVariable values(101,'John');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into UserVariable values(200,'Tom');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into UserVariable values(500,'Carol');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1827,
"s": 1744,
"text": "Display all records from the table using select command. The query is as follows −"
},
{
"code": null,
"e": 1861,
"s": 1827,
"text": "mysql> select *from UserVariable;"
},
{
"code": null,
"e": 2005,
"s": 1861,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | John |\n| 200 | Tom |\n| 500 | Carol |\n+------+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2222,
"s": 2005,
"text": "Write a query with a user variable that display the records with maximum id. First, I am going to create a variable and initialize this variable by selecting maximum id from the above table. The query is as follows −"
},
{
"code": null,
"e": 2313,
"s": 2222,
"text": "mysql> set @Maxid=(select MAX(Id) from UserVariable);\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2428,
"s": 2313,
"text": "After that, create another variable which has only name with that particular maximum id. The query is as follows −"
},
{
"code": null,
"e": 2531,
"s": 2428,
"text": "mysql> set @Name=(select Name from UserVariable where Id=@Maxid);\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2615,
"s": 2531,
"text": "Now you can check what value is present in variable Name. The query is as follows −"
},
{
"code": null,
"e": 2636,
"s": 2615,
"text": "mysql> select @Name;"
},
{
"code": null,
"e": 2709,
"s": 2636,
"text": "The following is the output that displays the name with the highest Id −"
},
{
"code": null,
"e": 2783,
"s": 2709,
"text": "+-------+\n| @Name |\n+-------+\n| Carol |\n+-------+\n1 row in set (0.00 sec)"
}
]
|
Bootstrap class pull-right | Float an element to the right with class pull-right.
You can try to run the following code to implement the pull-right class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "pull-right">
Float to right
</div>
</body>
</html> | [
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Float an element to the right with class pull-right."
},
{
"code": null,
"e": 1187,
"s": 1115,
"text": "You can try to run the following code to implement the pull-right class"
},
{
"code": null,
"e": 1197,
"s": 1187,
"text": "Live Demo"
},
{
"code": null,
"e": 1571,
"s": 1197,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"pull-right\">\n Float to right\n </div>\n </body>\n</html>"
}
]
|
Jackson Annotations - @JsonIgnore | @JsonIgnore is used at field level to mark a property or list of properties to be ignored.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
try{
Student student = new Student(1,11,"1ab","Mark");
String jsonString = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(student);
System.out.println(jsonString);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
public int id;
@JsonIgnore
public String systemId;
public int rollNo;
public String name;
Student(int id, int rollNo, String systemId, String name){
this.id = id;
this.systemId = systemId;
this.rollNo = rollNo;
this.name = name;
}
}
{
"id" : 1,
"rollNo" : 11,
"name" : "Mark"
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2566,
"s": 2475,
"text": "@JsonIgnore is used at field level to mark a property or list of properties to be ignored."
},
{
"code": null,
"e": 3446,
"s": 2566,
"text": "import java.io.IOException;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n ObjectMapper mapper = new ObjectMapper();\n try{\n Student student = new Student(1,11,\"1ab\",\"Mark\"); \n String jsonString = mapper\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n }\n catch (IOException e) { \n e.printStackTrace();\n } \n }\n}\nclass Student { \n public int id;\n @JsonIgnore\n public String systemId;\n public int rollNo;\n public String name;\n\n Student(int id, int rollNo, String systemId, String name){\n this.id = id;\n this.systemId = systemId;\n this.rollNo = rollNo;\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 3501,
"s": 3446,
"text": "{\n \"id\" : 1,\n \"rollNo\" : 11,\n \"name\" : \"Mark\"\n}\n"
},
{
"code": null,
"e": 3508,
"s": 3501,
"text": " Print"
},
{
"code": null,
"e": 3519,
"s": 3508,
"text": " Add Notes"
}
]
|
Program to generate Pascal's triangle in Python | Suppose we have a number n. We have to generate Pascal's triangle up to n lines. The Pascal's triangle will be look like this −
The property of Pascal's triangle is the sum of each adjacent two numbers of previous row is the value of the number which is placed just below on the second row. For example, the first 10 at row 6 is sum of 4 and 6 at row 5 and second 10 is sum of two numbers 6 and 4 at row 5.
So, if the input is like n = 5, then the output will be
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
To solve this, we will follow these steps −
for i in range 0 to n+1, dofor j in range 0 to n-i, doprint one blank spaceC := 1for j in range 1 to i+1, doprint C then a single blank spaceC := quotient of (C *(i - j) / j)go to next line
for j in range 0 to n-i, doprint one blank space
print one blank space
C := 1
for j in range 1 to i+1, doprint C then a single blank spaceC := quotient of (C *(i - j) / j)
print C then a single blank space
C := quotient of (C *(i - j) / j)
go to next line
Let us see the following implementation to get better understanding −
def solve(n):
for i in range(n+1):
for j in range(n-i):
print(' ', end='')
C = 1
for j in range(1, i+1):
print(C, ' ', sep='', end='')
C = C * (i - j) // j
print()
n = 5
solve(n)
5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Suppose we have a number n. We have to generate Pascal's triangle up to n lines. The Pascal's triangle will be look like this −"
},
{
"code": null,
"e": 1469,
"s": 1190,
"text": "The property of Pascal's triangle is the sum of each adjacent two numbers of previous row is the value of the number which is placed just below on the second row. For example, the first 10 at row 6 is sum of 4 and 6 at row 5 and second 10 is sum of two numbers 6 and 4 at row 5."
},
{
"code": null,
"e": 1525,
"s": 1469,
"text": "So, if the input is like n = 5, then the output will be"
},
{
"code": null,
"e": 1565,
"s": 1525,
"text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n1 4 6 4 1"
},
{
"code": null,
"e": 1609,
"s": 1565,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1799,
"s": 1609,
"text": "for i in range 0 to n+1, dofor j in range 0 to n-i, doprint one blank spaceC := 1for j in range 1 to i+1, doprint C then a single blank spaceC := quotient of (C *(i - j) / j)go to next line"
},
{
"code": null,
"e": 1848,
"s": 1799,
"text": "for j in range 0 to n-i, doprint one blank space"
},
{
"code": null,
"e": 1870,
"s": 1848,
"text": "print one blank space"
},
{
"code": null,
"e": 1877,
"s": 1870,
"text": "C := 1"
},
{
"code": null,
"e": 1971,
"s": 1877,
"text": "for j in range 1 to i+1, doprint C then a single blank spaceC := quotient of (C *(i - j) / j)"
},
{
"code": null,
"e": 2005,
"s": 1971,
"text": "print C then a single blank space"
},
{
"code": null,
"e": 2039,
"s": 2005,
"text": "C := quotient of (C *(i - j) / j)"
},
{
"code": null,
"e": 2055,
"s": 2039,
"text": "go to next line"
},
{
"code": null,
"e": 2125,
"s": 2055,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2360,
"s": 2125,
"text": "def solve(n):\n for i in range(n+1):\n for j in range(n-i):\n print(' ', end='')\n\n C = 1\n for j in range(1, i+1):\n print(C, ' ', sep='', end='')\n C = C * (i - j) // j\n print()\n\nn = 5\nsolve(n)"
},
{
"code": null,
"e": 2362,
"s": 2360,
"text": "5"
},
{
"code": null,
"e": 2402,
"s": 2362,
"text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n1 4 6 4 1"
}
]
|
Accelerate Geospatial Data Science With These Tricks | by Abdishakur | Towards Data Science | In this era of big data, large datasets are ubiquitous rather than being the exception. Although you can use some other accelerating techniques in data science, Geographic data science have special techniques to boost up your geodata processing. In this article, I share some of my favourite tips and tricks to accelerate geospatial data processing in Python.
Throughout this tutorial, we use NYC taxi trips dataset. The data contains 1.4 million points. We also use taxi zones dataset to do some geoprocessing tasks. We first read the data with Geopandas for benchmarking.
Let us import libraries we use in this tutorial.
import geopandas as gpdimport matplotlib.pyplot as pltimport geofeatherimport datashader as dsimport holoviews as hv
Reading the data takes quite some time, depending on the computation resources. At my end, this took 1 minute and 46 seconds.
We can speed up reading time by converting the data format (Shapefile) to GeoFeather format.
Now this will boost your reading speed, but it only takes one line of code to convert your data to GeoFeather, thanks to Geofeather library. Let us transform the data to GeoFeather.
geofeather.to_geofeather(gdf,'tutorialData/TaxiDataGeoFeather.feather')
Converting to GeoFeather takes only 51 seconds in my case, but that is it, and next time you can read the data with Geofeather, and it takes less time than reading from shapefile. Let us see that.
gdf = geofeather.from_geofeather(‘tutorialData/TaxiDataGeoFeather.feather’)
Reading with Geofeather took only 26 seconds compared to 1 minute and 46 seconds while using Shapefiles. It is a wonderful technique and helps you experiment fast with geospatial data without waiting a long time.
I also find sometimes to read only a subset of geometry based on my needs. It was not possible before Geopandas 0.70 released recently. The second tip shows you how to read a subset geometry with a large dataset.
Let us read first the taxi zones and plot them with taxi points we read in the previous section.
zones = gpd.read_file(“tutorialData/taxizones.shp”)fig, ax = plt.subplots(figsize=(12,10))zones.plot(“borough”, ax=ax, legend=True)gdf.sample(5000).plot(ax=ax, markersize=2, color=”black”)
The following map shows a sample of taxi points overlayed on taxi zones(coloured by borough).
Now, imagine you need only Brooklyn borough, and it is unnecessary to read the whole data. In that case, you need only to read a subset of the data with geometry. You can do that by providing a mask while reading the data with Geopandas.
gdf_subset = gpd.read_file(“tutorialData/taxidata.shp”, mask=zones[zones[“borough”].isin([“Brooklyn”])])
This took only 38 seconds, and you only get what you need, a subset of taxi points data that are within Brooklyn polygon only.
Sometimes, spatial indexes might help you speed up your geoprocessing tasks. Let us see speed differences between the spatial index and non-spatial index implementation of Point In Polygon(PIP) example. We first dissolve the taxi zones into borough polygons and then do spatial join without spatial index.
boroughs = zones.dissolve(by=’borough’)sjoined = gpd.sjoin(gdf, boroughs, op=”within”)
Without a spatial index, the process takes 2 minutes and 50 seconds in my case. Let us see if the spatial index might boost performance speed.
To create a spatial index in Geopandas is very easy. Let us do that for both datasets.
gdf_sindexed = gdfzones_sindexed = zonesgdf_sindexed.sindexzones_sindexed.sindex
And now we do PIP processing with Spatial Index.
sjoined = gpd.sjoin(gdf_sindexed, boroughs_sindexed, op="within")
With the spatial index, the process takes 2 minutes 19 seconds which is a little improvement in speed compared to non-spatial index processing. Spatial Indexes do not always help, especially where points data and polygons have the same extent. You can read a detailed explanation on when spatial indexes work and when they don’t from this blog post.
Plotting large datasets often ends up with frustration when using other plotting libraries, like Folium or Plotly. Datashader is specific for plotting large datasets.
Datashader is a graphics pipeline system for creating meaningful representations of large datasets quickly and flexibly.
This allows you to plot all your data on a map without compromising by taking a sample of it. Let us plot all 1.4 million points quickly and easily with Datashader.
agg = ds.Canvas().points(sjoined, ‘pickup_lon’, ‘pickup_lat’)img = tf.set_background(tf.shade(agg, cmap=fire),”black”)img
And what you get is this beautiful point map of all the data.
You can create interactive maps with beautiful base maps in Datashader. It also works well PyViz tools for data visualization like Geoviews and can combine with Panel to create beautiful dashboards with Jupyter notebooks.
In this article, I have shared some of my favourite boosting techniques in Geospatial data science with Python. You can speed up reading time with Geofeather or reading only the subset. For the geoprocessing task, it is worth trying to use the spatial index to speed up the processing time. And finally, to plot large dataset, use Datashader for speed and beautiful maps.
The notebook for this tutorial is here in Github. | [
{
"code": null,
"e": 532,
"s": 172,
"text": "In this era of big data, large datasets are ubiquitous rather than being the exception. Although you can use some other accelerating techniques in data science, Geographic data science have special techniques to boost up your geodata processing. In this article, I share some of my favourite tips and tricks to accelerate geospatial data processing in Python."
},
{
"code": null,
"e": 746,
"s": 532,
"text": "Throughout this tutorial, we use NYC taxi trips dataset. The data contains 1.4 million points. We also use taxi zones dataset to do some geoprocessing tasks. We first read the data with Geopandas for benchmarking."
},
{
"code": null,
"e": 795,
"s": 746,
"text": "Let us import libraries we use in this tutorial."
},
{
"code": null,
"e": 912,
"s": 795,
"text": "import geopandas as gpdimport matplotlib.pyplot as pltimport geofeatherimport datashader as dsimport holoviews as hv"
},
{
"code": null,
"e": 1038,
"s": 912,
"text": "Reading the data takes quite some time, depending on the computation resources. At my end, this took 1 minute and 46 seconds."
},
{
"code": null,
"e": 1131,
"s": 1038,
"text": "We can speed up reading time by converting the data format (Shapefile) to GeoFeather format."
},
{
"code": null,
"e": 1313,
"s": 1131,
"text": "Now this will boost your reading speed, but it only takes one line of code to convert your data to GeoFeather, thanks to Geofeather library. Let us transform the data to GeoFeather."
},
{
"code": null,
"e": 1385,
"s": 1313,
"text": "geofeather.to_geofeather(gdf,'tutorialData/TaxiDataGeoFeather.feather')"
},
{
"code": null,
"e": 1582,
"s": 1385,
"text": "Converting to GeoFeather takes only 51 seconds in my case, but that is it, and next time you can read the data with Geofeather, and it takes less time than reading from shapefile. Let us see that."
},
{
"code": null,
"e": 1658,
"s": 1582,
"text": "gdf = geofeather.from_geofeather(‘tutorialData/TaxiDataGeoFeather.feather’)"
},
{
"code": null,
"e": 1871,
"s": 1658,
"text": "Reading with Geofeather took only 26 seconds compared to 1 minute and 46 seconds while using Shapefiles. It is a wonderful technique and helps you experiment fast with geospatial data without waiting a long time."
},
{
"code": null,
"e": 2084,
"s": 1871,
"text": "I also find sometimes to read only a subset of geometry based on my needs. It was not possible before Geopandas 0.70 released recently. The second tip shows you how to read a subset geometry with a large dataset."
},
{
"code": null,
"e": 2181,
"s": 2084,
"text": "Let us read first the taxi zones and plot them with taxi points we read in the previous section."
},
{
"code": null,
"e": 2370,
"s": 2181,
"text": "zones = gpd.read_file(“tutorialData/taxizones.shp”)fig, ax = plt.subplots(figsize=(12,10))zones.plot(“borough”, ax=ax, legend=True)gdf.sample(5000).plot(ax=ax, markersize=2, color=”black”)"
},
{
"code": null,
"e": 2464,
"s": 2370,
"text": "The following map shows a sample of taxi points overlayed on taxi zones(coloured by borough)."
},
{
"code": null,
"e": 2702,
"s": 2464,
"text": "Now, imagine you need only Brooklyn borough, and it is unnecessary to read the whole data. In that case, you need only to read a subset of the data with geometry. You can do that by providing a mask while reading the data with Geopandas."
},
{
"code": null,
"e": 2807,
"s": 2702,
"text": "gdf_subset = gpd.read_file(“tutorialData/taxidata.shp”, mask=zones[zones[“borough”].isin([“Brooklyn”])])"
},
{
"code": null,
"e": 2934,
"s": 2807,
"text": "This took only 38 seconds, and you only get what you need, a subset of taxi points data that are within Brooklyn polygon only."
},
{
"code": null,
"e": 3240,
"s": 2934,
"text": "Sometimes, spatial indexes might help you speed up your geoprocessing tasks. Let us see speed differences between the spatial index and non-spatial index implementation of Point In Polygon(PIP) example. We first dissolve the taxi zones into borough polygons and then do spatial join without spatial index."
},
{
"code": null,
"e": 3327,
"s": 3240,
"text": "boroughs = zones.dissolve(by=’borough’)sjoined = gpd.sjoin(gdf, boroughs, op=”within”)"
},
{
"code": null,
"e": 3470,
"s": 3327,
"text": "Without a spatial index, the process takes 2 minutes and 50 seconds in my case. Let us see if the spatial index might boost performance speed."
},
{
"code": null,
"e": 3557,
"s": 3470,
"text": "To create a spatial index in Geopandas is very easy. Let us do that for both datasets."
},
{
"code": null,
"e": 3638,
"s": 3557,
"text": "gdf_sindexed = gdfzones_sindexed = zonesgdf_sindexed.sindexzones_sindexed.sindex"
},
{
"code": null,
"e": 3687,
"s": 3638,
"text": "And now we do PIP processing with Spatial Index."
},
{
"code": null,
"e": 3753,
"s": 3687,
"text": "sjoined = gpd.sjoin(gdf_sindexed, boroughs_sindexed, op=\"within\")"
},
{
"code": null,
"e": 4103,
"s": 3753,
"text": "With the spatial index, the process takes 2 minutes 19 seconds which is a little improvement in speed compared to non-spatial index processing. Spatial Indexes do not always help, especially where points data and polygons have the same extent. You can read a detailed explanation on when spatial indexes work and when they don’t from this blog post."
},
{
"code": null,
"e": 4270,
"s": 4103,
"text": "Plotting large datasets often ends up with frustration when using other plotting libraries, like Folium or Plotly. Datashader is specific for plotting large datasets."
},
{
"code": null,
"e": 4391,
"s": 4270,
"text": "Datashader is a graphics pipeline system for creating meaningful representations of large datasets quickly and flexibly."
},
{
"code": null,
"e": 4556,
"s": 4391,
"text": "This allows you to plot all your data on a map without compromising by taking a sample of it. Let us plot all 1.4 million points quickly and easily with Datashader."
},
{
"code": null,
"e": 4678,
"s": 4556,
"text": "agg = ds.Canvas().points(sjoined, ‘pickup_lon’, ‘pickup_lat’)img = tf.set_background(tf.shade(agg, cmap=fire),”black”)img"
},
{
"code": null,
"e": 4740,
"s": 4678,
"text": "And what you get is this beautiful point map of all the data."
},
{
"code": null,
"e": 4962,
"s": 4740,
"text": "You can create interactive maps with beautiful base maps in Datashader. It also works well PyViz tools for data visualization like Geoviews and can combine with Panel to create beautiful dashboards with Jupyter notebooks."
},
{
"code": null,
"e": 5334,
"s": 4962,
"text": "In this article, I have shared some of my favourite boosting techniques in Geospatial data science with Python. You can speed up reading time with Geofeather or reading only the subset. For the geoprocessing task, it is worth trying to use the spatial index to speed up the processing time. And finally, to plot large dataset, use Datashader for speed and beautiful maps."
}
]
|
How to remove Specific Element from a Swift Array? | To remove a specific object from an element in swift, we can use multiple ways of doing it. Let’s see this in the playground with help of an example.
First, let’s create an array of String.
var arrayOfString = ["a","b","c","f"]
We’ll do it with the following methods as shown below:
Arrays in swift have a filter method, which filters the array object depending on some conditions and returns an array of new objects.
let modifiedArray = arrayOfString.filter { $0 != "f" }
print(modifiedArray)
When we run the above code, we get the following result.
Now, we’ll use the indexPath of the object to remove it from the array.
if arrayOfString.contains("c") {
let index = arrayOfString.firstIndex(of: "c")
arrayOfString.remove(at: index!)
print(arrayOfString)
}
When we run the above code, we get the following result.
Let’s see one more example of both methods, with numbers.
var arry = [1,2,6,44]
let modifiedArray = arry.filter { $0 != 6 }
print(modifiedArray)
if arry.contains(1) {
let index = arry.firstIndex(of: 1)
arry.remove(at: index!)
print(arry)
}
We get the following output when we run the above code. | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "To remove a specific object from an element in swift, we can use multiple ways of doing it. Let’s see this in the playground with help of an example."
},
{
"code": null,
"e": 1252,
"s": 1212,
"text": "First, let’s create an array of String."
},
{
"code": null,
"e": 1290,
"s": 1252,
"text": "var arrayOfString = [\"a\",\"b\",\"c\",\"f\"]"
},
{
"code": null,
"e": 1345,
"s": 1290,
"text": "We’ll do it with the following methods as shown below:"
},
{
"code": null,
"e": 1480,
"s": 1345,
"text": "Arrays in swift have a filter method, which filters the array object depending on some conditions and returns an array of new objects."
},
{
"code": null,
"e": 1556,
"s": 1480,
"text": "let modifiedArray = arrayOfString.filter { $0 != \"f\" }\nprint(modifiedArray)"
},
{
"code": null,
"e": 1613,
"s": 1556,
"text": "When we run the above code, we get the following result."
},
{
"code": null,
"e": 1685,
"s": 1613,
"text": "Now, we’ll use the indexPath of the object to remove it from the array."
},
{
"code": null,
"e": 1829,
"s": 1685,
"text": "if arrayOfString.contains(\"c\") {\n let index = arrayOfString.firstIndex(of: \"c\")\n arrayOfString.remove(at: index!)\n print(arrayOfString)\n}"
},
{
"code": null,
"e": 1886,
"s": 1829,
"text": "When we run the above code, we get the following result."
},
{
"code": null,
"e": 1944,
"s": 1886,
"text": "Let’s see one more example of both methods, with numbers."
},
{
"code": null,
"e": 2135,
"s": 1944,
"text": "var arry = [1,2,6,44]\nlet modifiedArray = arry.filter { $0 != 6 }\nprint(modifiedArray)\nif arry.contains(1) {\n let index = arry.firstIndex(of: 1)\n arry.remove(at: index!)\n print(arry)\n}"
},
{
"code": null,
"e": 2191,
"s": 2135,
"text": "We get the following output when we run the above code."
}
]
|
TestNG - Writing Tests | Writing a test in TestNG basically involves the following steps −
Write the business logic of your test and insert TestNG annotations in your code.
Write the business logic of your test and insert TestNG annotations in your code.
Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml.
Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml.
Run TestNG.
Run TestNG.
Here, we will see one complete example of TestNG testing using POJO class, Business logic class and a test xml, which will be run by TestNG.
Create EmployeeDetails.java in /work/testng/src, which is a POJO class.
public class EmployeeDetails {
private String name;
private double monthlySalary;
private int age;
// @return the name
public String getName() {
return name;
}
// @param name the name to set
public void setName(String name) {
this.name = name;
}
// @return the monthlySalary
public double getMonthlySalary() {
return monthlySalary;
}
// @param monthlySalary the monthlySalary to set
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
// @return the age
public int getAge() {
return age;
}
// @param age the age to set
public void setAge(int age) {
this.age = age;
}
}
EmployeeDetails class is used to −
get/set the value of employee's name.
get/set the value of employee's monthly salary.
get/set the value of employee's age.
Create an EmpBusinessLogic.java in /work/testng/src, which contains business logic.
public class EmpBusinessLogic {
// Calculate the yearly salary of employee
public double calculateYearlySalary(EmployeeDetails employeeDetails) {
double yearlySalary = 0;
yearlySalary = employeeDetails.getMonthlySalary() * 12;
return yearlySalary;
}
// Calculate the appraisal amount of employee
public double calculateAppraisal(EmployeeDetails employeeDetails) {
double appraisal = 0;
if(employeeDetails.getMonthlySalary() < 10000) {
appraisal = 500;
} else {
appraisal = 1000;
}
return appraisal;
}
}
EmpBusinessLogic class is used for calculating −
the yearly salary of employee.
the appraisal amount of employee.
Now, let's create a TestNG class called TestEmployeeDetails.java in /work/testng/src. A TestNG class is a Java class that contains at least one TestNG annotation. This class contains test cases to be tested. A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations (we will see this in the chapter TestNG - Execution Procedure), which allows to perform some Java logic before and after a certain point.
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestEmployeeDetails {
EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic();
EmployeeDetails employee = new EmployeeDetails();
@Test
public void testCalculateAppriasal() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double appraisal = empBusinessLogic.calculateAppraisal(employee);
Assert.assertEquals(500, appraisal, 0.0, "500");
}
// Test to check yearly salary
@Test
public void testCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary = empBusinessLogic.calculateYearlySalary(employee);
Assert.assertEquals(96000, salary, 0.0, "8000");
}
}
TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It does the following −
Tests the yearly salary of the employee.
Tests the yearly salary of the employee.
Tests the appraisal amount of the employee.
Tests the appraisal amount of the employee.
Before you can run the tests, you must configure TestNG using a special XML file, conventionally named testng.xml. The syntax for this file is very simple, and its contents are as shown below. Create this file in /work/testng/src.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "TestEmployeeDetails"/>
</classes>
</test>
</suite>
Details of the above file are as follows −
A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag.
A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag.
Tag <test> represents one test and can contain one or more TestNG classes.
Tag <test> represents one test and can contain one or more TestNG classes.
<class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods.
<class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods.
Compile the Test case classes using javac.
/work/testng/src$ javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java
Now TestNG with the following command −
/work/testng/src$ java org.testng.TestNG testng.xml
If all has been done correctly, you should see the results of your tests in the console. Furthermore, TestNG creates a very nice HTML report in a folder called test-output that is automatically created in the current directory. If you open it and load index.html, you will see a page similar to the one in the image below −
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2126,
"s": 2060,
"text": "Writing a test in TestNG basically involves the following steps −"
},
{
"code": null,
"e": 2208,
"s": 2126,
"text": "Write the business logic of your test and insert TestNG annotations in your code."
},
{
"code": null,
"e": 2290,
"s": 2208,
"text": "Write the business logic of your test and insert TestNG annotations in your code."
},
{
"code": null,
"e": 2420,
"s": 2290,
"text": "Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml."
},
{
"code": null,
"e": 2550,
"s": 2420,
"text": "Add the information about your test (e.g. the class name, the groups you wish to run, etc.) in a testng.xml file or in build.xml."
},
{
"code": null,
"e": 2562,
"s": 2550,
"text": "Run TestNG."
},
{
"code": null,
"e": 2574,
"s": 2562,
"text": "Run TestNG."
},
{
"code": null,
"e": 2715,
"s": 2574,
"text": "Here, we will see one complete example of TestNG testing using POJO class, Business logic class and a test xml, which will be run by TestNG."
},
{
"code": null,
"e": 2787,
"s": 2715,
"text": "Create EmployeeDetails.java in /work/testng/src, which is a POJO class."
},
{
"code": null,
"e": 3507,
"s": 2787,
"text": "public class EmployeeDetails {\n\n private String name;\n private double monthlySalary;\n private int age;\n\n // @return the name\n\n public String getName() {\n return name;\n }\n\n // @param name the name to set\n\n public void setName(String name) {\n this.name = name;\n }\n\n // @return the monthlySalary\n\n public double getMonthlySalary() {\n return monthlySalary;\n }\n\n // @param monthlySalary the monthlySalary to set\n\n public void setMonthlySalary(double monthlySalary) {\n this.monthlySalary = monthlySalary;\n }\n\n // @return the age\n\n public int getAge() {\n return age;\n }\n\n // @param age the age to set\n\n public void setAge(int age) {\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 3542,
"s": 3507,
"text": "EmployeeDetails class is used to −"
},
{
"code": null,
"e": 3580,
"s": 3542,
"text": "get/set the value of employee's name."
},
{
"code": null,
"e": 3628,
"s": 3580,
"text": "get/set the value of employee's monthly salary."
},
{
"code": null,
"e": 3665,
"s": 3628,
"text": "get/set the value of employee's age."
},
{
"code": null,
"e": 3749,
"s": 3665,
"text": "Create an EmpBusinessLogic.java in /work/testng/src, which contains business logic."
},
{
"code": null,
"e": 4342,
"s": 3749,
"text": "public class EmpBusinessLogic {\n\n // Calculate the yearly salary of employee\n public double calculateYearlySalary(EmployeeDetails employeeDetails) {\n double yearlySalary = 0;\n yearlySalary = employeeDetails.getMonthlySalary() * 12;\n return yearlySalary;\n }\n\n // Calculate the appraisal amount of employee\n public double calculateAppraisal(EmployeeDetails employeeDetails) {\n\n double appraisal = 0;\n\n if(employeeDetails.getMonthlySalary() < 10000) {\n appraisal = 500;\n\n } else {\n appraisal = 1000;\n }\n\n return appraisal;\n }\n}"
},
{
"code": null,
"e": 4391,
"s": 4342,
"text": "EmpBusinessLogic class is used for calculating −"
},
{
"code": null,
"e": 4422,
"s": 4391,
"text": "the yearly salary of employee."
},
{
"code": null,
"e": 4456,
"s": 4422,
"text": "the appraisal amount of employee."
},
{
"code": null,
"e": 4874,
"s": 4456,
"text": "Now, let's create a TestNG class called TestEmployeeDetails.java in /work/testng/src. A TestNG class is a Java class that contains at least one TestNG annotation. This class contains test cases to be tested. A TestNG test can be configured by @BeforeXXX and @AfterXXX annotations (we will see this in the chapter TestNG - Execution Procedure), which allows to perform some Java logic before and after a certain point."
},
{
"code": null,
"e": 5699,
"s": 4874,
"text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class TestEmployeeDetails {\n EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic();\n EmployeeDetails employee = new EmployeeDetails();\n\n @Test\n public void testCalculateAppriasal() {\n\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\n double appraisal = empBusinessLogic.calculateAppraisal(employee);\n Assert.assertEquals(500, appraisal, 0.0, \"500\");\n }\n\n // Test to check yearly salary\n @Test\n public void testCalculateYearlySalary() {\n\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\n double salary = empBusinessLogic.calculateYearlySalary(employee);\n Assert.assertEquals(96000, salary, 0.0, \"8000\");\n }\n}"
},
{
"code": null,
"e": 5809,
"s": 5699,
"text": "TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It does the following −"
},
{
"code": null,
"e": 5850,
"s": 5809,
"text": "Tests the yearly salary of the employee."
},
{
"code": null,
"e": 5891,
"s": 5850,
"text": "Tests the yearly salary of the employee."
},
{
"code": null,
"e": 5935,
"s": 5891,
"text": "Tests the appraisal amount of the employee."
},
{
"code": null,
"e": 5979,
"s": 5935,
"text": "Tests the appraisal amount of the employee."
},
{
"code": null,
"e": 6210,
"s": 5979,
"text": "Before you can run the tests, you must configure TestNG using a special XML file, conventionally named testng.xml. The syntax for this file is very simple, and its contents are as shown below. Create this file in /work/testng/src."
},
{
"code": null,
"e": 6463,
"s": 6210,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"TestEmployeeDetails\"/>\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 6506,
"s": 6463,
"text": "Details of the above file are as follows −"
},
{
"code": null,
"e": 6614,
"s": 6506,
"text": "A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag."
},
{
"code": null,
"e": 6722,
"s": 6614,
"text": "A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag."
},
{
"code": null,
"e": 6797,
"s": 6722,
"text": "Tag <test> represents one test and can contain one or more TestNG classes."
},
{
"code": null,
"e": 6872,
"s": 6797,
"text": "Tag <test> represents one test and can contain one or more TestNG classes."
},
{
"code": null,
"e": 7017,
"s": 6872,
"text": "<class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods."
},
{
"code": null,
"e": 7162,
"s": 7017,
"text": "<class> tag represents a TestNG class. It is a Java class that contains at least one TestNG annotation. It can contain one or more test methods."
},
{
"code": null,
"e": 7205,
"s": 7162,
"text": "Compile the Test case classes using javac."
},
{
"code": null,
"e": 7298,
"s": 7205,
"text": "/work/testng/src$ javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java\n"
},
{
"code": null,
"e": 7338,
"s": 7298,
"text": "Now TestNG with the following command −"
},
{
"code": null,
"e": 7391,
"s": 7338,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 7715,
"s": 7391,
"text": "If all has been done correctly, you should see the results of your tests in the console. Furthermore, TestNG creates a very nice HTML report in a folder called test-output that is automatically created in the current directory. If you open it and load index.html, you will see a page similar to the one in the image below −"
},
{
"code": null,
"e": 7750,
"s": 7715,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7764,
"s": 7750,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7799,
"s": 7764,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7817,
"s": 7799,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 7850,
"s": 7817,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7870,
"s": 7850,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 7877,
"s": 7870,
"text": " Print"
},
{
"code": null,
"e": 7888,
"s": 7877,
"text": " Add Notes"
}
]
|
Sort an arrays of 0’s, 1’s and 2’s using C++ | Given an array of 0, 1, and 2, sort the elements in an order such that all the zeros come first before 1 and all the 2’s in the end. We have to sort all the elements of the array in-place.
We can solve this problem using DNF (Dutch National Flag) Sorting Algorithm. For example,
Input-1 −
arr[ ]= {2,0,0,1,2,1 }
Output −
0 0 1 1 2 2
Explanation − Sorting the given array of elements containing 0,1 and 2 using DNF Sorting Algorithm, it will print the output as {0,0,1,1,2,2}.
Input-2 −
arr[ ]= {0,1,1,2,1,1,0}
Output −
0 0 1 1 1 1 2
Explanation − Sorting the given array of elements containing 0,1 and 2 using the DNF Sorting Algorithm, it will print the output as {0,0,1,1,1,1,2}.
In the given array of 0, 1 and 2, we can use the DNF sorting algorithm.
DNF Sorting Algorithm − The algorithm requires 3 pointers to iterate throughout the array by swapping the necessary elements.
Create a low pointer at the beginning of the array and high pointer pointing at the end of the array.
Create a low pointer at the beginning of the array and high pointer pointing at the end of the array.
Find the Midpoint of the array and create a mid pointer as well that iterates from the beginning of the array till the end.
Find the Midpoint of the array and create a mid pointer as well that iterates from the beginning of the array till the end.
If the mid-pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer.
If the mid-pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer.
If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer.
If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer.
If the mid-pointer of the array is ‘1’, then increase the mid pointer.
If the mid-pointer of the array is ‘1’, then increase the mid pointer.
Live Demo
#include<iostream>
using namespace std;
void dnfsort(int a[], int n){
int low= 0;
int high= n-1;
int mid=0;
while(mid<=high){
if(a[mid]==0){
swap(a[mid],a[low]);
mid++;
low++;
}
if(a[mid]==1){
mid++;
}
if(a[mid]==2){
swap(a[mid],a[high]);
high--;
}
}
}
int main(){
int a[]= {1,0,0,2,1,1,0,0,1};
int n= sizeof(a)/sizeof(int);
dnfsort(a,n);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
Running the above code will generate the output as,
0 0 0 0 1 1 1 1 2 | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Given an array of 0, 1, and 2, sort the elements in an order such that all the zeros come first before 1 and all the 2’s in the end. We have to sort all the elements of the array in-place."
},
{
"code": null,
"e": 1341,
"s": 1251,
"text": "We can solve this problem using DNF (Dutch National Flag) Sorting Algorithm. For example,"
},
{
"code": null,
"e": 1351,
"s": 1341,
"text": "Input-1 −"
},
{
"code": null,
"e": 1374,
"s": 1351,
"text": "arr[ ]= {2,0,0,1,2,1 }"
},
{
"code": null,
"e": 1383,
"s": 1374,
"text": "Output −"
},
{
"code": null,
"e": 1395,
"s": 1383,
"text": "0 0 1 1 2 2"
},
{
"code": null,
"e": 1538,
"s": 1395,
"text": "Explanation − Sorting the given array of elements containing 0,1 and 2 using DNF Sorting Algorithm, it will print the output as {0,0,1,1,2,2}."
},
{
"code": null,
"e": 1548,
"s": 1538,
"text": "Input-2 −"
},
{
"code": null,
"e": 1572,
"s": 1548,
"text": "arr[ ]= {0,1,1,2,1,1,0}"
},
{
"code": null,
"e": 1581,
"s": 1572,
"text": "Output −"
},
{
"code": null,
"e": 1595,
"s": 1581,
"text": "0 0 1 1 1 1 2"
},
{
"code": null,
"e": 1744,
"s": 1595,
"text": "Explanation − Sorting the given array of elements containing 0,1 and 2 using the DNF Sorting Algorithm, it will print the output as {0,0,1,1,1,1,2}."
},
{
"code": null,
"e": 1816,
"s": 1744,
"text": "In the given array of 0, 1 and 2, we can use the DNF sorting algorithm."
},
{
"code": null,
"e": 1942,
"s": 1816,
"text": "DNF Sorting Algorithm − The algorithm requires 3 pointers to iterate throughout the array by swapping the necessary elements."
},
{
"code": null,
"e": 2044,
"s": 1942,
"text": "Create a low pointer at the beginning of the array and high pointer pointing at the end of the array."
},
{
"code": null,
"e": 2146,
"s": 2044,
"text": "Create a low pointer at the beginning of the array and high pointer pointing at the end of the array."
},
{
"code": null,
"e": 2270,
"s": 2146,
"text": "Find the Midpoint of the array and create a mid pointer as well that iterates from the beginning of the array till the end."
},
{
"code": null,
"e": 2394,
"s": 2270,
"text": "Find the Midpoint of the array and create a mid pointer as well that iterates from the beginning of the array till the end."
},
{
"code": null,
"e": 2516,
"s": 2394,
"text": "If the mid-pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer."
},
{
"code": null,
"e": 2638,
"s": 2516,
"text": "If the mid-pointer of the array is ‘0’, then swap the element pointing at low. Increment the low pointer and mid pointer."
},
{
"code": null,
"e": 2788,
"s": 2638,
"text": "If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer."
},
{
"code": null,
"e": 2938,
"s": 2788,
"text": "If the mid-pointer of the array is ‘2’, then swap it with the element pointing at the high. Increment the mid pointer and decrement the high pointer."
},
{
"code": null,
"e": 3009,
"s": 2938,
"text": "If the mid-pointer of the array is ‘1’, then increase the mid pointer."
},
{
"code": null,
"e": 3080,
"s": 3009,
"text": "If the mid-pointer of the array is ‘1’, then increase the mid pointer."
},
{
"code": null,
"e": 3091,
"s": 3080,
"text": " Live Demo"
},
{
"code": null,
"e": 3612,
"s": 3091,
"text": "#include<iostream>\nusing namespace std;\nvoid dnfsort(int a[], int n){\n int low= 0;\n int high= n-1;\n int mid=0;\n while(mid<=high){\n if(a[mid]==0){\n swap(a[mid],a[low]);\n mid++;\n low++;\n }\n if(a[mid]==1){\n mid++;\n }\n if(a[mid]==2){\n swap(a[mid],a[high]);\n high--;\n }\n }\n}\nint main(){\n int a[]= {1,0,0,2,1,1,0,0,1};\n int n= sizeof(a)/sizeof(int);\n dnfsort(a,n);\n for(int i=0;i<n;i++){\n cout<<a[i]<<\" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 3664,
"s": 3612,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 3682,
"s": 3664,
"text": "0 0 0 0 1 1 1 1 2"
}
]
|
Java Program to create rounded borders in Swing | Let us first create a Frame:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
Now, create rounded borders:
double x = 50;
double y = 50;
frame.setShape(new RoundRectangle2D.Double(x, y, 100, 100, 50, 50));
The following is an example to create rounded borders in Swing:
import java.awt.geom.RoundRectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
double x = 50;
double y = 50;
frame.setShape(new RoundRectangle2D.Double(x, y, 100, 100, 50, 50));
frame.setSize(600, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1091,
"s": 1062,
"text": "Let us first create a Frame:"
},
{
"code": null,
"e": 1202,
"s": 1091,
"text": "JFrame frame = new JFrame();\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\nframe.setUndecorated(true);"
},
{
"code": null,
"e": 1231,
"s": 1202,
"text": "Now, create rounded borders:"
},
{
"code": null,
"e": 1331,
"s": 1231,
"text": "double x = 50;\ndouble y = 50;\n\nframe.setShape(new RoundRectangle2D.Double(x, y, 100, 100, 50, 50));"
},
{
"code": null,
"e": 1395,
"s": 1331,
"text": "The following is an example to create rounded borders in Swing:"
},
{
"code": null,
"e": 1927,
"s": 1395,
"text": "import java.awt.geom.RoundRectangle2D;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\npublic class SwingDemo extends JPanel {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setUndecorated(true);\n double x = 50;\n double y = 50;\n frame.setShape(new RoundRectangle2D.Double(x, y, 100, 100, 50, 50));\n frame.setSize(600, 500);\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n }\n}"
}
]
|
Program to print number pattern in C | A numerical pattern is a sequence of numbers that have been created based on a rule called a pattern rule. Pattern rules can use one or more mathematical operations to describe the relationship between consecutive numbers in the sequence.
Examples for Patterns
Pattern 1
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Pattern 2
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
Pattern 1:
i stands for rows and j stands for columns.
5 stands for making pattern for 5 Rows and Columns
Loop for each Row (i)
K is initialized to i
Loop for each Column (j)
Do the Pattern for the current Column (j)
Display the Value of K
Reinitialize the Value of K = k + 5 - j
Pattern 2:
First Row: Display 1
Second Row: Display 1,2,3
Third Row: Display 1,2,3,4,5
Fourth Row: Display 1,2,3,4,5,6,7
Fifth Row: Display 1,2,3,4,5,6,7,8,9
Display the same contents from 4th Row till First Row below the fifth Row.
/* Program to print Numeric Pattern */
#include<stdio.h>
int main(){
int i,j,k;
printf("Numeric Pattern 1");
printf("\n");
printf("\n");
for(i=1;i<=5;i++){
k = i;
for(j=1;j<=i;j++){
printf("%d ", k);
k += 5-j;
}
printf("\n");
}
printf("\n");
printf("Numeric Pattern 2");
printf("\n");
printf("\n");
for(i = 1;i<=5;i++){
for(j = i;j<5;j++){
printf(" ");
}
for(k = 1;k<(i*2);k++){
printf("%d",k);
}
printf("\n");
}
for(i = 4;i>=1;i--){
for(j = 5;j>i;j--){
printf(" ");
}
for(k = 1;k<(i*2);k++){
printf("%d",k);
}
printf("\n");
}
getch();
return 0;
} | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "A numerical pattern is a sequence of numbers that have been created based on a rule called a pattern rule. Pattern rules can use one or more mathematical operations to describe the relationship between consecutive numbers in the sequence."
},
{
"code": null,
"e": 1323,
"s": 1301,
"text": "Examples for Patterns"
},
{
"code": null,
"e": 1333,
"s": 1323,
"text": "Pattern 1"
},
{
"code": null,
"e": 1369,
"s": 1333,
"text": "1\n2 6\n3 7 10\n4 8 11 13\n5 9 12 14 15"
},
{
"code": null,
"e": 1379,
"s": 1369,
"text": "Pattern 2"
},
{
"code": null,
"e": 1501,
"s": 1379,
"text": " 1\n 1 2 3\n 1 2 3 4 5\n 1 2 3 4 5 6 7\n1 2 3 4 5 6 7 8 9\n 1 2 3 4 5 6 7\n 1 2 3 4 5\n 1 2 3\n 1"
},
{
"code": null,
"e": 2014,
"s": 1501,
"text": "Pattern 1:\ni stands for rows and j stands for columns.\n5 stands for making pattern for 5 Rows and Columns\nLoop for each Row (i)\nK is initialized to i\nLoop for each Column (j)\nDo the Pattern for the current Column (j)\nDisplay the Value of K\nReinitialize the Value of K = k + 5 - j\nPattern 2:\nFirst Row: Display 1\nSecond Row: Display 1,2,3\nThird Row: Display 1,2,3,4,5\nFourth Row: Display 1,2,3,4,5,6,7\nFifth Row: Display 1,2,3,4,5,6,7,8,9\nDisplay the same contents from 4th Row till First Row below the fifth Row."
},
{
"code": null,
"e": 2748,
"s": 2014,
"text": "/* Program to print Numeric Pattern */\n#include<stdio.h>\nint main(){\n int i,j,k;\n printf(\"Numeric Pattern 1\");\n printf(\"\\n\");\n printf(\"\\n\");\n for(i=1;i<=5;i++){\n k = i;\n for(j=1;j<=i;j++){\n printf(\"%d \", k);\n k += 5-j;\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n printf(\"Numeric Pattern 2\");\n printf(\"\\n\");\n printf(\"\\n\");\n for(i = 1;i<=5;i++){\n for(j = i;j<5;j++){\n printf(\" \");\n }\n for(k = 1;k<(i*2);k++){\n printf(\"%d\",k);\n }\n printf(\"\\n\");\n }\n for(i = 4;i>=1;i--){\n for(j = 5;j>i;j--){\n printf(\" \");\n }\n for(k = 1;k<(i*2);k++){\n printf(\"%d\",k);\n }\n printf(\"\\n\");\n }\n getch();\n return 0;\n}"
}
]
|
Insert Delete GetRandom O(1) in Python | Suppose we have a data structure that supports all following operations in average O(1) time.
insert(val) − This will Insert an item val to the set if that is not already present.
insert(val) − This will Insert an item val to the set if that is not already present.
remove(val) − This will remove an item val from the set if it presents.
remove(val) − This will remove an item val from the set if it presents.
getRandom − This will return a random element from current set of elements. Each element must have the same probability of being returned.
getRandom − This will return a random element from current set of elements. Each element must have the same probability of being returned.
To solve this, we will follow these steps −
For the initialization, define a parent map, and elements array
For the initialization, define a parent map, and elements array
For the insert() function, it will take val as inputif val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true
For the insert() function, it will take val as input
if val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true
if val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true
return false
return false
For the remove() method, it will take val to remove
For the remove() method, it will take val to remove
if val is not present in parent map, or parent[val] = 0, then return false
if val is not present in parent map, or parent[val] = 0, then return false
set parent[val] := 0
set parent[val] := 0
index := index of val in elements array
index := index of val in elements array
if index is not same as length of elements – 1temp := last element of elementsset last element of elements := valset elements[index] := temp
if index is not same as length of elements – 1
temp := last element of elements
temp := last element of elements
set last element of elements := val
set last element of elements := val
set elements[index] := temp
set elements[index] := temp
delete last element of elements
delete last element of elements
The getRandom() method will return any random value present in elements array
The getRandom() method will return any random value present in elements array
Let us see the following implementation to get a better understanding −
Live Demo
import random
class RandomizedSet(object):
def __init__(self):
self.present = {}
self.elements = []
def insert(self, val):
if val not in self.present or self.present[val] == 0:
self.elements.append(val)
self.present[val] = 1
return True
return False
def remove(self, val):
if val not in self.present or self.present[val] == 0:
return False
self.present[val] = 0
index = self.elements.index(val)
if index!=len(self.elements)-1:
temp = self.elements[-1]
self.elements[-1] = val
self.elements[index]=temp
self.elements.pop()
return True
def getRandom(self):
return random.choice(self.elements)
ob = RandomizedSet()
print(ob.insert(1))
print(ob.remove(2))
print(ob.insert(2))
print(ob.getRandom())
print(ob.remove(1))
print(ob.insert(2))
print(ob.getRandom())
Initialize the class, then call the insert(), remove(), getRandom() functions. See the implementation.
True
False
True
2
True
False
2 | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Suppose we have a data structure that supports all following operations in average O(1) time."
},
{
"code": null,
"e": 1242,
"s": 1156,
"text": "insert(val) − This will Insert an item val to the set if that is not already present."
},
{
"code": null,
"e": 1328,
"s": 1242,
"text": "insert(val) − This will Insert an item val to the set if that is not already present."
},
{
"code": null,
"e": 1400,
"s": 1328,
"text": "remove(val) − This will remove an item val from the set if it presents."
},
{
"code": null,
"e": 1472,
"s": 1400,
"text": "remove(val) − This will remove an item val from the set if it presents."
},
{
"code": null,
"e": 1611,
"s": 1472,
"text": "getRandom − This will return a random element from current set of elements. Each element must have the same probability of being returned."
},
{
"code": null,
"e": 1750,
"s": 1611,
"text": "getRandom − This will return a random element from current set of elements. Each element must have the same probability of being returned."
},
{
"code": null,
"e": 1794,
"s": 1750,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1858,
"s": 1794,
"text": "For the initialization, define a parent map, and elements array"
},
{
"code": null,
"e": 1922,
"s": 1858,
"text": "For the initialization, define a parent map, and elements array"
},
{
"code": null,
"e": 2104,
"s": 1922,
"text": "For the insert() function, it will take val as inputif val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true"
},
{
"code": null,
"e": 2157,
"s": 2104,
"text": "For the insert() function, it will take val as input"
},
{
"code": null,
"e": 2287,
"s": 2157,
"text": "if val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true"
},
{
"code": null,
"e": 2417,
"s": 2287,
"text": "if val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true"
},
{
"code": null,
"e": 2430,
"s": 2417,
"text": "return false"
},
{
"code": null,
"e": 2443,
"s": 2430,
"text": "return false"
},
{
"code": null,
"e": 2495,
"s": 2443,
"text": "For the remove() method, it will take val to remove"
},
{
"code": null,
"e": 2547,
"s": 2495,
"text": "For the remove() method, it will take val to remove"
},
{
"code": null,
"e": 2622,
"s": 2547,
"text": "if val is not present in parent map, or parent[val] = 0, then return false"
},
{
"code": null,
"e": 2697,
"s": 2622,
"text": "if val is not present in parent map, or parent[val] = 0, then return false"
},
{
"code": null,
"e": 2718,
"s": 2697,
"text": "set parent[val] := 0"
},
{
"code": null,
"e": 2739,
"s": 2718,
"text": "set parent[val] := 0"
},
{
"code": null,
"e": 2779,
"s": 2739,
"text": "index := index of val in elements array"
},
{
"code": null,
"e": 2819,
"s": 2779,
"text": "index := index of val in elements array"
},
{
"code": null,
"e": 2960,
"s": 2819,
"text": "if index is not same as length of elements – 1temp := last element of elementsset last element of elements := valset elements[index] := temp"
},
{
"code": null,
"e": 3007,
"s": 2960,
"text": "if index is not same as length of elements – 1"
},
{
"code": null,
"e": 3040,
"s": 3007,
"text": "temp := last element of elements"
},
{
"code": null,
"e": 3073,
"s": 3040,
"text": "temp := last element of elements"
},
{
"code": null,
"e": 3109,
"s": 3073,
"text": "set last element of elements := val"
},
{
"code": null,
"e": 3145,
"s": 3109,
"text": "set last element of elements := val"
},
{
"code": null,
"e": 3173,
"s": 3145,
"text": "set elements[index] := temp"
},
{
"code": null,
"e": 3201,
"s": 3173,
"text": "set elements[index] := temp"
},
{
"code": null,
"e": 3233,
"s": 3201,
"text": "delete last element of elements"
},
{
"code": null,
"e": 3265,
"s": 3233,
"text": "delete last element of elements"
},
{
"code": null,
"e": 3343,
"s": 3265,
"text": "The getRandom() method will return any random value present in elements array"
},
{
"code": null,
"e": 3421,
"s": 3343,
"text": "The getRandom() method will return any random value present in elements array"
},
{
"code": null,
"e": 3493,
"s": 3421,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 3504,
"s": 3493,
"text": " Live Demo"
},
{
"code": null,
"e": 4401,
"s": 3504,
"text": "import random\nclass RandomizedSet(object):\n def __init__(self):\n self.present = {}\n self.elements = []\n def insert(self, val):\n if val not in self.present or self.present[val] == 0:\n self.elements.append(val)\n self.present[val] = 1\n return True\n return False\n def remove(self, val):\n if val not in self.present or self.present[val] == 0:\n return False\n self.present[val] = 0\n index = self.elements.index(val)\n if index!=len(self.elements)-1:\n temp = self.elements[-1]\n self.elements[-1] = val\n self.elements[index]=temp\n self.elements.pop()\n return True\n def getRandom(self):\n return random.choice(self.elements)\nob = RandomizedSet()\nprint(ob.insert(1))\nprint(ob.remove(2))\nprint(ob.insert(2))\nprint(ob.getRandom())\nprint(ob.remove(1))\nprint(ob.insert(2))\nprint(ob.getRandom())"
},
{
"code": null,
"e": 4504,
"s": 4401,
"text": "Initialize the class, then call the insert(), remove(), getRandom() functions. See the implementation."
},
{
"code": null,
"e": 4535,
"s": 4504,
"text": "True\nFalse\nTrue\n2\nTrue\nFalse\n2"
}
]
|
Pyspark — forecasting with Pandas UDF and fb-prophet | by Alexandre Wrg | Towards Data Science | Before starting anything to work with pandas-udf the prerequisite are
spark ≥ 2.4
pyarrow ≤ 0.14.1 (above this version there’s some issue)
then we need to set up an environment variable for pyarrow to 1. (see import code)
sudo pip3 install pyarrow=0.14.1
Then we can proceed to libraries import.
from pyspark.sql import SparkSessionfrom pyspark.sql.types import *from pyspark.sql.functions import pandas_udf, PandasUDFType, sum, max, col, concat, litimport sysimport os# setup to work around with pandas udf# see answers here https://stackoverflow.com/questions/58458415/pandas-scalar-udf-failing-illegalargumentexceptionos.environ["ARROW_PRE_0_15_IPC_FORMAT"] = "1"from fbprophet import Prophetimport pandas as pdimport numpy as np
If everything going well we can call the spark context through “sc” and see :
Now we can talk about the interesting part, the forecast!
In this tutorial we will use the new features of pyspark: the pandas-udf, like the good old pyspark UDF the pandas-udf is a user-defined function with the goal to apply our most favorite libraries like numpy, pandas, sklearn and more on Spark DataFrame without changing anything to the syntax and return a Spark DataFrame.
In particular, we will explore the GROUPED_MAP attributes of the Pandas UDF which allow us to apply scikit-learn, statsmodels and more to our Spark DataFrame. We will apply the popular Prophet piecewise regression of the Facebook AI to each item | store in our dataset using Pandas UDF without any loops and without any concatenation of results since Prophet does not process multiple time series at the same time.
Pandas_udf can be passed to the base function as a decorator that wraps the whole function with two parameters: the expected output schemas and the GROUPED_MAP attributes.
# define an output schemaschema = StructType([ StructField("store", StringType(), True), StructField("item", StringType(), True), StructField("ds", DateType(), True), StructField("yhat", DoubleType(), True) ])
With the decorator defined, the rest is very simple and intuitive; we define our function to adjust and forecast our data as we do for a single series.
My function is very simple, I accept as input a Spark dataframe which is the result of the concatenation of the training set and the test set (with the target initialized to null) which is my sales history for any item (the format is a Spark Dataframe). The function will be applied as if there was only one product-store pair and as a Pandas DataFrame so no syntax change, so we define the training and forecast dates and rename the dates and sales columns by the conventions requested by the algorithm, then I call my function that creates a national event dataframe (format: Pandas DataFrame). Then I pass everything in the algorithm, make the forecast and I attach my forecast dataframe which contains only the date and the forecast associated with my initial test set in order to retrieve the product and store id. The whole function is wrapped in pandas-udf and .. that’s it !
N.B: holidays in Prophet argument is just an “hard-coded” holiday pandas DataFrame available in the notebook.
We can train our model.
If all goes well, the console should log each time series that is trained with a few metrics.
Then, each series is predicted, we put it all together in a single Spark DataFrame without concatenation.
The magic works! We have predicted around 50 series of time series in a blink without complication, without for-loop and without retrieval of the results.
In this short tutorial, we see how to use pandas udf to train several models to forecast several time series at a time in a distributed manner. The main advantages of pandas UDF compared to the fact that it allows us to skip the loop and the concatenation part is the computing time we gain by doing it through a distributed framework, each time series is formed on a different partition on a different worker and the whole is gathered at the end, this is a real advantage compared to a loop that can take some time to run for millions of elements with real data.
the notebook is available on my Github here: https://github.com/AlexWarembourg/Medium and the data are available on Kaggle (the link is under comments in the notebook and the main thing. Thanks! | [
{
"code": null,
"e": 242,
"s": 172,
"text": "Before starting anything to work with pandas-udf the prerequisite are"
},
{
"code": null,
"e": 254,
"s": 242,
"text": "spark ≥ 2.4"
},
{
"code": null,
"e": 311,
"s": 254,
"text": "pyarrow ≤ 0.14.1 (above this version there’s some issue)"
},
{
"code": null,
"e": 394,
"s": 311,
"text": "then we need to set up an environment variable for pyarrow to 1. (see import code)"
},
{
"code": null,
"e": 427,
"s": 394,
"text": "sudo pip3 install pyarrow=0.14.1"
},
{
"code": null,
"e": 468,
"s": 427,
"text": "Then we can proceed to libraries import."
},
{
"code": null,
"e": 905,
"s": 468,
"text": "from pyspark.sql import SparkSessionfrom pyspark.sql.types import *from pyspark.sql.functions import pandas_udf, PandasUDFType, sum, max, col, concat, litimport sysimport os# setup to work around with pandas udf# see answers here https://stackoverflow.com/questions/58458415/pandas-scalar-udf-failing-illegalargumentexceptionos.environ[\"ARROW_PRE_0_15_IPC_FORMAT\"] = \"1\"from fbprophet import Prophetimport pandas as pdimport numpy as np"
},
{
"code": null,
"e": 983,
"s": 905,
"text": "If everything going well we can call the spark context through “sc” and see :"
},
{
"code": null,
"e": 1041,
"s": 983,
"text": "Now we can talk about the interesting part, the forecast!"
},
{
"code": null,
"e": 1364,
"s": 1041,
"text": "In this tutorial we will use the new features of pyspark: the pandas-udf, like the good old pyspark UDF the pandas-udf is a user-defined function with the goal to apply our most favorite libraries like numpy, pandas, sklearn and more on Spark DataFrame without changing anything to the syntax and return a Spark DataFrame."
},
{
"code": null,
"e": 1779,
"s": 1364,
"text": "In particular, we will explore the GROUPED_MAP attributes of the Pandas UDF which allow us to apply scikit-learn, statsmodels and more to our Spark DataFrame. We will apply the popular Prophet piecewise regression of the Facebook AI to each item | store in our dataset using Pandas UDF without any loops and without any concatenation of results since Prophet does not process multiple time series at the same time."
},
{
"code": null,
"e": 1951,
"s": 1779,
"text": "Pandas_udf can be passed to the base function as a decorator that wraps the whole function with two parameters: the expected output schemas and the GROUPED_MAP attributes."
},
{
"code": null,
"e": 2192,
"s": 1951,
"text": "# define an output schemaschema = StructType([ StructField(\"store\", StringType(), True), StructField(\"item\", StringType(), True), StructField(\"ds\", DateType(), True), StructField(\"yhat\", DoubleType(), True) ])"
},
{
"code": null,
"e": 2344,
"s": 2192,
"text": "With the decorator defined, the rest is very simple and intuitive; we define our function to adjust and forecast our data as we do for a single series."
},
{
"code": null,
"e": 3227,
"s": 2344,
"text": "My function is very simple, I accept as input a Spark dataframe which is the result of the concatenation of the training set and the test set (with the target initialized to null) which is my sales history for any item (the format is a Spark Dataframe). The function will be applied as if there was only one product-store pair and as a Pandas DataFrame so no syntax change, so we define the training and forecast dates and rename the dates and sales columns by the conventions requested by the algorithm, then I call my function that creates a national event dataframe (format: Pandas DataFrame). Then I pass everything in the algorithm, make the forecast and I attach my forecast dataframe which contains only the date and the forecast associated with my initial test set in order to retrieve the product and store id. The whole function is wrapped in pandas-udf and .. that’s it !"
},
{
"code": null,
"e": 3337,
"s": 3227,
"text": "N.B: holidays in Prophet argument is just an “hard-coded” holiday pandas DataFrame available in the notebook."
},
{
"code": null,
"e": 3361,
"s": 3337,
"text": "We can train our model."
},
{
"code": null,
"e": 3455,
"s": 3361,
"text": "If all goes well, the console should log each time series that is trained with a few metrics."
},
{
"code": null,
"e": 3561,
"s": 3455,
"text": "Then, each series is predicted, we put it all together in a single Spark DataFrame without concatenation."
},
{
"code": null,
"e": 3716,
"s": 3561,
"text": "The magic works! We have predicted around 50 series of time series in a blink without complication, without for-loop and without retrieval of the results."
},
{
"code": null,
"e": 4280,
"s": 3716,
"text": "In this short tutorial, we see how to use pandas udf to train several models to forecast several time series at a time in a distributed manner. The main advantages of pandas UDF compared to the fact that it allows us to skip the loop and the concatenation part is the computing time we gain by doing it through a distributed framework, each time series is formed on a different partition on a different worker and the whole is gathered at the end, this is a real advantage compared to a loop that can take some time to run for millions of elements with real data."
}
]
|
How to Supercharge Excel With Python | by Costas Andreou | Towards Data Science | As much as Excel is a blessing, it is also a curse. When it comes to smallish enough data and simple enough operations Excel is king. Once you find yourself endeavoring outside of those zones however, it becomes a pain. Sure enough, you can use Excel VBA to get around such issues, but in the year 2020, you can thank your lucky stars because you don’t have to!
If only there was a way to integrate Excel with Python to give Excel... wings! Well, now there is. A python library called xlwings allows you to call Python scripts through VBA and pass data between the two.
The truth of the matter is, you can pretty much do anything in VBA. So, if that is the case, why would you want to use Python? Well, there are a number of reasons.
You can create a custom function in Excel without learning VBA (if you don’t know it already)Your users are comfortable in ExcelYou can speed up your data operations significantly by using PythonThere are libraries for just about anything in Python (Machine Learning, Data Science, etc)Because you can!!!
You can create a custom function in Excel without learning VBA (if you don’t know it already)
Your users are comfortable in Excel
You can speed up your data operations significantly by using Python
There are libraries for just about anything in Python (Machine Learning, Data Science, etc)
Because you can!!!
The first thing we need to do, as with any new library we want to use, is to install it. It’s super easy to do; with two commands we’ll be set up in no time. So, go ahead and type in your terminal:
Once the library has been downloaded and installed, we need to install the Excel integration part. Ensure you’ve closed down all your Excel instances and in any terminal type:
Assuming you experience no errors, you should be able to proceed. However, oftentimes on Win10 with Excel 2016, people will see the following error:
xlwings 0.17.0[Errno 2] No such file or directory: 'C:\\Users\\costa\\AppData\\Roaming\\Microsoft\\Excel\\XLSTART\\xlwings.xlam'
If you are one of the lucky ones to experience the above error, all you need to do is create the missing directory. You can do that easily by using the mkdir command. In my case, I did:
mkdir C:\\Users\\costa\\AppData\\Roaming\\Microsoft\\Excel\\XLSTART
Assuming the successful installation of the excel integration with the python library, the main difference you will immediately notice is in Excel:
First up, we need to load the Excel Add-in. You can hit Alt, L, H and then navigate to the directory above to load the plugin. Once you’re done, you should be able to see the following:
Finally, you need to Enable Trust access to the VBA project object model. You can do that by navigating to File > Options > Trust Center > Trust Center Settings > Macro Settings:
There are two main ways you can go from Excel to Python (and back). The first one is to call a Python script directly from VBA, while the other one is through a User Defined Function. Let us have a quick look at both.
In order to avoid any confusion and to have the correct set up every time, xlwings offers to create your Excel spreadsheet, ready to go. Let us then use this functionality. Using the terminal, we navigate to the directory we like and type:
xlwings quickstart ProjectName
I am calling this MyFirstPythonXL. The above command will create a new folder in your pre-navigated directory with an Excel worksheet and a python file.
Opening the .xlsm file, you immediately notice a new Excel sheet called _xlwings.conf. Should you wish to override the default settings of xlwings, all you have to do is rename this sheet and remove the starting underscore. And with that, we are all set up and ready to begin using xlwings.
Before we jump into the coding, let us first ensure we are all on the same page. To bring up our Excel VBA editor, hit Alt + F11. This should return the following screen:
The key things to note here is that this code will do the following:
Look for a Python Script in the same location as the spreadsheetLook for a Python Script with the same name as the spreadsheet (but with a .py extension)From the Python Script, call the function “main()”
Look for a Python Script in the same location as the spreadsheet
Look for a Python Script with the same name as the spreadsheet (but with a .py extension)
From the Python Script, call the function “main()”
Without any further ado, let us look at a few examples of how this can be used.
In this example, we will see how you carry operations outside of Excel, but then return your results in the spreadsheet. This can have an infinite amount of use cases.
We will source data from a CSV file, do a modification on said data, and then pass the output to Excel. Let’s review how easy it is:
First up, the VBA code:
I have left this completely unchanged from the default.
Then, the Python code:
Which results in the following:
In this example, we will read inputs from Excel, do something with it in Python, and then pass the result back to Excel.
More specifically, we are going to read a Greeting, a Name and a file location of where we can find jokes. Our Python script will then take a random line from the file, and return us a joke.
First up, the VBA code:
I have left this completely unchanged from the default.
Then, the Python code:
Which gives us:
In pretty much the same fashion as before, we will be changing the code in the python file. In order to turn something into an Excel User Defined Function, all we need to do is include ‘@xw.func’ before the line the function is on:
The Python code:
The result:
I think you would agree that this is a nifty little library. If you are like me and you much prefer to work in Python rather than VBA but need to work in spreadsheets, then this can be an exceptional tool.
Want to stay up to date with my blogs? Don’t forget to follow me!
Here are some of the other articles which you might find interesting: | [
{
"code": null,
"e": 534,
"s": 172,
"text": "As much as Excel is a blessing, it is also a curse. When it comes to smallish enough data and simple enough operations Excel is king. Once you find yourself endeavoring outside of those zones however, it becomes a pain. Sure enough, you can use Excel VBA to get around such issues, but in the year 2020, you can thank your lucky stars because you don’t have to!"
},
{
"code": null,
"e": 742,
"s": 534,
"text": "If only there was a way to integrate Excel with Python to give Excel... wings! Well, now there is. A python library called xlwings allows you to call Python scripts through VBA and pass data between the two."
},
{
"code": null,
"e": 906,
"s": 742,
"text": "The truth of the matter is, you can pretty much do anything in VBA. So, if that is the case, why would you want to use Python? Well, there are a number of reasons."
},
{
"code": null,
"e": 1211,
"s": 906,
"text": "You can create a custom function in Excel without learning VBA (if you don’t know it already)Your users are comfortable in ExcelYou can speed up your data operations significantly by using PythonThere are libraries for just about anything in Python (Machine Learning, Data Science, etc)Because you can!!!"
},
{
"code": null,
"e": 1305,
"s": 1211,
"text": "You can create a custom function in Excel without learning VBA (if you don’t know it already)"
},
{
"code": null,
"e": 1341,
"s": 1305,
"text": "Your users are comfortable in Excel"
},
{
"code": null,
"e": 1409,
"s": 1341,
"text": "You can speed up your data operations significantly by using Python"
},
{
"code": null,
"e": 1501,
"s": 1409,
"text": "There are libraries for just about anything in Python (Machine Learning, Data Science, etc)"
},
{
"code": null,
"e": 1520,
"s": 1501,
"text": "Because you can!!!"
},
{
"code": null,
"e": 1718,
"s": 1520,
"text": "The first thing we need to do, as with any new library we want to use, is to install it. It’s super easy to do; with two commands we’ll be set up in no time. So, go ahead and type in your terminal:"
},
{
"code": null,
"e": 1894,
"s": 1718,
"text": "Once the library has been downloaded and installed, we need to install the Excel integration part. Ensure you’ve closed down all your Excel instances and in any terminal type:"
},
{
"code": null,
"e": 2043,
"s": 1894,
"text": "Assuming you experience no errors, you should be able to proceed. However, oftentimes on Win10 with Excel 2016, people will see the following error:"
},
{
"code": null,
"e": 2172,
"s": 2043,
"text": "xlwings 0.17.0[Errno 2] No such file or directory: 'C:\\\\Users\\\\costa\\\\AppData\\\\Roaming\\\\Microsoft\\\\Excel\\\\XLSTART\\\\xlwings.xlam'"
},
{
"code": null,
"e": 2358,
"s": 2172,
"text": "If you are one of the lucky ones to experience the above error, all you need to do is create the missing directory. You can do that easily by using the mkdir command. In my case, I did:"
},
{
"code": null,
"e": 2426,
"s": 2358,
"text": "mkdir C:\\\\Users\\\\costa\\\\AppData\\\\Roaming\\\\Microsoft\\\\Excel\\\\XLSTART"
},
{
"code": null,
"e": 2574,
"s": 2426,
"text": "Assuming the successful installation of the excel integration with the python library, the main difference you will immediately notice is in Excel:"
},
{
"code": null,
"e": 2760,
"s": 2574,
"text": "First up, we need to load the Excel Add-in. You can hit Alt, L, H and then navigate to the directory above to load the plugin. Once you’re done, you should be able to see the following:"
},
{
"code": null,
"e": 2939,
"s": 2760,
"text": "Finally, you need to Enable Trust access to the VBA project object model. You can do that by navigating to File > Options > Trust Center > Trust Center Settings > Macro Settings:"
},
{
"code": null,
"e": 3157,
"s": 2939,
"text": "There are two main ways you can go from Excel to Python (and back). The first one is to call a Python script directly from VBA, while the other one is through a User Defined Function. Let us have a quick look at both."
},
{
"code": null,
"e": 3397,
"s": 3157,
"text": "In order to avoid any confusion and to have the correct set up every time, xlwings offers to create your Excel spreadsheet, ready to go. Let us then use this functionality. Using the terminal, we navigate to the directory we like and type:"
},
{
"code": null,
"e": 3428,
"s": 3397,
"text": "xlwings quickstart ProjectName"
},
{
"code": null,
"e": 3581,
"s": 3428,
"text": "I am calling this MyFirstPythonXL. The above command will create a new folder in your pre-navigated directory with an Excel worksheet and a python file."
},
{
"code": null,
"e": 3872,
"s": 3581,
"text": "Opening the .xlsm file, you immediately notice a new Excel sheet called _xlwings.conf. Should you wish to override the default settings of xlwings, all you have to do is rename this sheet and remove the starting underscore. And with that, we are all set up and ready to begin using xlwings."
},
{
"code": null,
"e": 4043,
"s": 3872,
"text": "Before we jump into the coding, let us first ensure we are all on the same page. To bring up our Excel VBA editor, hit Alt + F11. This should return the following screen:"
},
{
"code": null,
"e": 4112,
"s": 4043,
"text": "The key things to note here is that this code will do the following:"
},
{
"code": null,
"e": 4316,
"s": 4112,
"text": "Look for a Python Script in the same location as the spreadsheetLook for a Python Script with the same name as the spreadsheet (but with a .py extension)From the Python Script, call the function “main()”"
},
{
"code": null,
"e": 4381,
"s": 4316,
"text": "Look for a Python Script in the same location as the spreadsheet"
},
{
"code": null,
"e": 4471,
"s": 4381,
"text": "Look for a Python Script with the same name as the spreadsheet (but with a .py extension)"
},
{
"code": null,
"e": 4522,
"s": 4471,
"text": "From the Python Script, call the function “main()”"
},
{
"code": null,
"e": 4602,
"s": 4522,
"text": "Without any further ado, let us look at a few examples of how this can be used."
},
{
"code": null,
"e": 4770,
"s": 4602,
"text": "In this example, we will see how you carry operations outside of Excel, but then return your results in the spreadsheet. This can have an infinite amount of use cases."
},
{
"code": null,
"e": 4903,
"s": 4770,
"text": "We will source data from a CSV file, do a modification on said data, and then pass the output to Excel. Let’s review how easy it is:"
},
{
"code": null,
"e": 4927,
"s": 4903,
"text": "First up, the VBA code:"
},
{
"code": null,
"e": 4983,
"s": 4927,
"text": "I have left this completely unchanged from the default."
},
{
"code": null,
"e": 5006,
"s": 4983,
"text": "Then, the Python code:"
},
{
"code": null,
"e": 5038,
"s": 5006,
"text": "Which results in the following:"
},
{
"code": null,
"e": 5159,
"s": 5038,
"text": "In this example, we will read inputs from Excel, do something with it in Python, and then pass the result back to Excel."
},
{
"code": null,
"e": 5350,
"s": 5159,
"text": "More specifically, we are going to read a Greeting, a Name and a file location of where we can find jokes. Our Python script will then take a random line from the file, and return us a joke."
},
{
"code": null,
"e": 5374,
"s": 5350,
"text": "First up, the VBA code:"
},
{
"code": null,
"e": 5430,
"s": 5374,
"text": "I have left this completely unchanged from the default."
},
{
"code": null,
"e": 5453,
"s": 5430,
"text": "Then, the Python code:"
},
{
"code": null,
"e": 5469,
"s": 5453,
"text": "Which gives us:"
},
{
"code": null,
"e": 5701,
"s": 5469,
"text": "In pretty much the same fashion as before, we will be changing the code in the python file. In order to turn something into an Excel User Defined Function, all we need to do is include ‘@xw.func’ before the line the function is on:"
},
{
"code": null,
"e": 5718,
"s": 5701,
"text": "The Python code:"
},
{
"code": null,
"e": 5730,
"s": 5718,
"text": "The result:"
},
{
"code": null,
"e": 5936,
"s": 5730,
"text": "I think you would agree that this is a nifty little library. If you are like me and you much prefer to work in Python rather than VBA but need to work in spreadsheets, then this can be an exceptional tool."
},
{
"code": null,
"e": 6002,
"s": 5936,
"text": "Want to stay up to date with my blogs? Don’t forget to follow me!"
}
]
|
F# Azure Functions. Creating Azure Functions in F# | by Ian Ormesher | Towards Data Science | F# is a great language and is also a good choice for programming your Azure Functions. Unfortunately, Microsoft hasn’t made it easy to implement them. It’s certainly easier than it used to be, but there’s a bit of work to get things set up at the beginning. But I would argue it’s well worth the effort!
To start you’ll need to have the Azure CLI installed on your machine. If you haven’t already got this, click on the link below:
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
This will enable you to use the Azure CLI from the Windows Command Line or a PowerShell prompt. I prefer the PowerShell prompt because this also gives you TAB completion.
From a PowerShell prompt type the following to get a list of the currently installed Azure templates for F#:
dotnet new --list -lang F#
You should see something like this:
First, we’ll create our project template for the Azure function from the prompt:
dotnet new func -lang F# --name AzureFunctionFSharp
This will create 4 files:
Of all the Azure Function templates available, the easiest one to use is the HttpTrigger. To create this from the prompt:
dotnet new http -lang F# --name HttpTrigger
This will create the HttpTrigger.fs
Once you’ve done all this the next step is to create the solution file in Visual Studio 2019. If you open the project file AzureFunctionFSharp.fsproj you should find almost everything you’ve added so far:
However, you’ll notice it doesn’t have our HttpTrigger.fs file! Simply add this file to the project. You also need to add the hosts.json and localhost.settings.json. For these last two files you must ensure that their Build Action is None and they are copied to the output directory if newer:
Once you’ve done that, build the project and save the solution.
I find the FSharp.Data NuGet package extremely helpful when working with F# projects. You can add this through the Manage Packages option for the project.
Having done all of this you can save this whole project as a custom template for future projects. This will save you having to go through all of this again. If you select your project in the Solution Explorer tab and then choose Export Template from the Project menu you can export this project as a future template:
The next time you want to create an F# Azure Function project you can then use the custom template you’ve created:
If everything is set up correctly, you should now be able to press F5 and debug your project. You should see something like this:
You can then use something like Postman to send a request to the REST API and see your output.
As I said at the beginning, it’s not as straightforward as creating an Azure Function in C#, but it is certainly worth the effort. Hopefully, Microsoft will continue to improve their support for F# Azure Functions and put a proper template in Visual Studio 2019 or a future version. In the meantime, this is how you can do it yourself. | [
{
"code": null,
"e": 476,
"s": 172,
"text": "F# is a great language and is also a good choice for programming your Azure Functions. Unfortunately, Microsoft hasn’t made it easy to implement them. It’s certainly easier than it used to be, but there’s a bit of work to get things set up at the beginning. But I would argue it’s well worth the effort!"
},
{
"code": null,
"e": 604,
"s": 476,
"text": "To start you’ll need to have the Azure CLI installed on your machine. If you haven’t already got this, click on the link below:"
},
{
"code": null,
"e": 687,
"s": 604,
"text": "https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest"
},
{
"code": null,
"e": 858,
"s": 687,
"text": "This will enable you to use the Azure CLI from the Windows Command Line or a PowerShell prompt. I prefer the PowerShell prompt because this also gives you TAB completion."
},
{
"code": null,
"e": 967,
"s": 858,
"text": "From a PowerShell prompt type the following to get a list of the currently installed Azure templates for F#:"
},
{
"code": null,
"e": 994,
"s": 967,
"text": "dotnet new --list -lang F#"
},
{
"code": null,
"e": 1030,
"s": 994,
"text": "You should see something like this:"
},
{
"code": null,
"e": 1111,
"s": 1030,
"text": "First, we’ll create our project template for the Azure function from the prompt:"
},
{
"code": null,
"e": 1163,
"s": 1111,
"text": "dotnet new func -lang F# --name AzureFunctionFSharp"
},
{
"code": null,
"e": 1189,
"s": 1163,
"text": "This will create 4 files:"
},
{
"code": null,
"e": 1311,
"s": 1189,
"text": "Of all the Azure Function templates available, the easiest one to use is the HttpTrigger. To create this from the prompt:"
},
{
"code": null,
"e": 1355,
"s": 1311,
"text": "dotnet new http -lang F# --name HttpTrigger"
},
{
"code": null,
"e": 1391,
"s": 1355,
"text": "This will create the HttpTrigger.fs"
},
{
"code": null,
"e": 1596,
"s": 1391,
"text": "Once you’ve done all this the next step is to create the solution file in Visual Studio 2019. If you open the project file AzureFunctionFSharp.fsproj you should find almost everything you’ve added so far:"
},
{
"code": null,
"e": 1889,
"s": 1596,
"text": "However, you’ll notice it doesn’t have our HttpTrigger.fs file! Simply add this file to the project. You also need to add the hosts.json and localhost.settings.json. For these last two files you must ensure that their Build Action is None and they are copied to the output directory if newer:"
},
{
"code": null,
"e": 1953,
"s": 1889,
"text": "Once you’ve done that, build the project and save the solution."
},
{
"code": null,
"e": 2108,
"s": 1953,
"text": "I find the FSharp.Data NuGet package extremely helpful when working with F# projects. You can add this through the Manage Packages option for the project."
},
{
"code": null,
"e": 2425,
"s": 2108,
"text": "Having done all of this you can save this whole project as a custom template for future projects. This will save you having to go through all of this again. If you select your project in the Solution Explorer tab and then choose Export Template from the Project menu you can export this project as a future template:"
},
{
"code": null,
"e": 2540,
"s": 2425,
"text": "The next time you want to create an F# Azure Function project you can then use the custom template you’ve created:"
},
{
"code": null,
"e": 2670,
"s": 2540,
"text": "If everything is set up correctly, you should now be able to press F5 and debug your project. You should see something like this:"
},
{
"code": null,
"e": 2765,
"s": 2670,
"text": "You can then use something like Postman to send a request to the REST API and see your output."
}
]
|
Pythonic Way to Perform Statistics Across Multiple Variables with Xarray | by Luke Gloege, Ph.D. | Towards Data Science | Consider this, you have an ensemble of models stored in a Dataset (ds), with each ensemble member stored as a different variable. How would you take the ensemble average? If you have three members (ens1, ens2, ens3), one approach is to do this:
ens_mean = (ds['ens1'] + ds['ens2'] + ds['ens3']) / 3
Although this is fine for a small ensemble, there is a more Pythonic way to do this. Let’s pretend each member represents the monthly temperature at each location on the globe, what we really want is code that looks like this:
ens_mean = ds['temperature'].mean('ensemble')
This is clean, has fewer characters to type, and it is clear what the code is accomplishing.
In this post, I will demonstrate how to manipulate a Xarray Dataset so you can average across a new categorical variable. I expect anyone who uses Xarray to analyze geospatial data or ensemble models to find relevance in this post.
If you want to follow along, I will be using a Dataset populated with synthetic data to explain this concept. The code to this Dataset is below. Let’s pretend this Dataset represents monthly temperature output from different models with a 1-degree spatial resolution.
The Dataset’s info() is shown below. Notice that each ensemble member (ens1, ens2, ens3) is a different variable.
Now that we have an example Dataset, let’s merge all the members into a single variable named temperature with dimension (ensemble, time, lat, lon), where the new ensemble coordinate will provide access to each member. The code below accomplishes this task.
There is alot happening in this, let’s walk through it line-by-line.
variables = list(ds) → this creates a list of all the variable names in your Dataset. If you don’t need all the variables, then you can simply hardcode a list of variable names.
The second line does three things:
expand_dims(‘ensemble’, axis=0) → Takes each variable and adds a new dimension at the first axis position.assign_coords(ensemble=[var]) → Creates a new coordinate with the same name as the new dimension from the previous step. This also assigns the variable name to the coordinaterename("temperature") → Renames the variable to temperature
expand_dims(‘ensemble’, axis=0) → Takes each variable and adds a new dimension at the first axis position.
assign_coords(ensemble=[var]) → Creates a new coordinate with the same name as the new dimension from the previous step. This also assigns the variable name to the coordinate
rename("temperature") → Renames the variable to temperature
Notices this is done for each variable via list comprehension. If this is confusing, I encourage you to run this on on a single variable and look at how the object changes after each step. The code below can help with this.
var = 'ens1'expand = ds[var].expand_dims('ensemble',axis=0)assign = expand.assign_coords(ensemble=[var])rename = assign.rename('temperature')
You can then output expand, assign, and rename to see how the object changes after each step.
Once we have a list of DataArrays, we need to stitch them together along the ensemble dimension using xr.merge().
xr.merge(da_list) → This merges all the DataArrays together into a single Dataset. The new Dataset only has one variable (temperature) with all the DataArrays merged along the ensemble coordinate
The last two lines may not be necessary. Those lines preserve the global attributes in ds.
global_attrs = ds.attrsds_merged.attrs = global_attrs
The final Dataset will look like this:
There are multiple ways to merge variables onto a new dimension. Here is another approach.
Now that we have our merged Dataset we can easily perform statistics across ensemble members.
ds_merged[‘temperature’].mean(‘ensemble’)
ds_merged[‘temperature’].var(‘ensemble’)
If we want to plot just ens1, we can select it like this
ds_merged.sel(ensemble='ens1')
Although accessing individual ensemble members is slightly more cumbersome, I think the benefit of being able to perform statistics across the entire ensemble is more important.
In this section, I will describe two methods to generalize this technique. The code I present is merely meant to give you ideas on how to extend this post.
The first approach is to pipe() the function to a Dataset. This is more aptly applied to chaining multiple functions together. However, depending on the situation, you may want to pipe() a single function.
Another option is to extend Xarray by registering an accessor. In practice, this is done by simply adding a class decorator. This approach is appropriate if you are working on a set of special-purpose functions. For example, maybe you’re working on a class of methods for processing ensemble models. The code below shows how to decorate a class that has the var_merger() function.
Keep in mind that once you register an accessor you can not change it. For example, if you run this code in a notebook and then later decide to add another function to the class and re-run it, that new function will not be registered with the accessor. You would first have to restart the kernel for it to take effect. For that reason, registering an accessor is more appropriately placed in the code library.
You can use your new accessor on a Dataset (ds) like this:
ds_merged = ds.ensemble.var_merger()
Notice that the name of the class is irrelevant since it is the accessor name we supply to the Dataset.
Hopefully, this tutorial helps you work more efficiently with ensembles. At the time of writing, I was unable to find a one-liner approach to merge variables like this in the documentation as well as their “How do I...” section.
Xarray is extremely powerful and many “how do I...” questions can be solved with existing functions. Having said that, it can be tricky to find the right functions and chain them together in the right way to achieve the desired object.
Please let me know if you have comments/suggestions on ways to improve this post. Also, please let me know if you are aware of a more elegant solution to merging variables onto a common coordinate.
As always, I am happy to help troubleshoot any issues you may come across.
Thank you for reading and supporting Medium writers | [
{
"code": null,
"e": 416,
"s": 171,
"text": "Consider this, you have an ensemble of models stored in a Dataset (ds), with each ensemble member stored as a different variable. How would you take the ensemble average? If you have three members (ens1, ens2, ens3), one approach is to do this:"
},
{
"code": null,
"e": 470,
"s": 416,
"text": "ens_mean = (ds['ens1'] + ds['ens2'] + ds['ens3']) / 3"
},
{
"code": null,
"e": 697,
"s": 470,
"text": "Although this is fine for a small ensemble, there is a more Pythonic way to do this. Let’s pretend each member represents the monthly temperature at each location on the globe, what we really want is code that looks like this:"
},
{
"code": null,
"e": 743,
"s": 697,
"text": "ens_mean = ds['temperature'].mean('ensemble')"
},
{
"code": null,
"e": 836,
"s": 743,
"text": "This is clean, has fewer characters to type, and it is clear what the code is accomplishing."
},
{
"code": null,
"e": 1068,
"s": 836,
"text": "In this post, I will demonstrate how to manipulate a Xarray Dataset so you can average across a new categorical variable. I expect anyone who uses Xarray to analyze geospatial data or ensemble models to find relevance in this post."
},
{
"code": null,
"e": 1336,
"s": 1068,
"text": "If you want to follow along, I will be using a Dataset populated with synthetic data to explain this concept. The code to this Dataset is below. Let’s pretend this Dataset represents monthly temperature output from different models with a 1-degree spatial resolution."
},
{
"code": null,
"e": 1450,
"s": 1336,
"text": "The Dataset’s info() is shown below. Notice that each ensemble member (ens1, ens2, ens3) is a different variable."
},
{
"code": null,
"e": 1708,
"s": 1450,
"text": "Now that we have an example Dataset, let’s merge all the members into a single variable named temperature with dimension (ensemble, time, lat, lon), where the new ensemble coordinate will provide access to each member. The code below accomplishes this task."
},
{
"code": null,
"e": 1777,
"s": 1708,
"text": "There is alot happening in this, let’s walk through it line-by-line."
},
{
"code": null,
"e": 1955,
"s": 1777,
"text": "variables = list(ds) → this creates a list of all the variable names in your Dataset. If you don’t need all the variables, then you can simply hardcode a list of variable names."
},
{
"code": null,
"e": 1990,
"s": 1955,
"text": "The second line does three things:"
},
{
"code": null,
"e": 2330,
"s": 1990,
"text": "expand_dims(‘ensemble’, axis=0) → Takes each variable and adds a new dimension at the first axis position.assign_coords(ensemble=[var]) → Creates a new coordinate with the same name as the new dimension from the previous step. This also assigns the variable name to the coordinaterename(\"temperature\") → Renames the variable to temperature"
},
{
"code": null,
"e": 2437,
"s": 2330,
"text": "expand_dims(‘ensemble’, axis=0) → Takes each variable and adds a new dimension at the first axis position."
},
{
"code": null,
"e": 2612,
"s": 2437,
"text": "assign_coords(ensemble=[var]) → Creates a new coordinate with the same name as the new dimension from the previous step. This also assigns the variable name to the coordinate"
},
{
"code": null,
"e": 2672,
"s": 2612,
"text": "rename(\"temperature\") → Renames the variable to temperature"
},
{
"code": null,
"e": 2896,
"s": 2672,
"text": "Notices this is done for each variable via list comprehension. If this is confusing, I encourage you to run this on on a single variable and look at how the object changes after each step. The code below can help with this."
},
{
"code": null,
"e": 3038,
"s": 2896,
"text": "var = 'ens1'expand = ds[var].expand_dims('ensemble',axis=0)assign = expand.assign_coords(ensemble=[var])rename = assign.rename('temperature')"
},
{
"code": null,
"e": 3132,
"s": 3038,
"text": "You can then output expand, assign, and rename to see how the object changes after each step."
},
{
"code": null,
"e": 3246,
"s": 3132,
"text": "Once we have a list of DataArrays, we need to stitch them together along the ensemble dimension using xr.merge()."
},
{
"code": null,
"e": 3442,
"s": 3246,
"text": "xr.merge(da_list) → This merges all the DataArrays together into a single Dataset. The new Dataset only has one variable (temperature) with all the DataArrays merged along the ensemble coordinate"
},
{
"code": null,
"e": 3533,
"s": 3442,
"text": "The last two lines may not be necessary. Those lines preserve the global attributes in ds."
},
{
"code": null,
"e": 3587,
"s": 3533,
"text": "global_attrs = ds.attrsds_merged.attrs = global_attrs"
},
{
"code": null,
"e": 3626,
"s": 3587,
"text": "The final Dataset will look like this:"
},
{
"code": null,
"e": 3717,
"s": 3626,
"text": "There are multiple ways to merge variables onto a new dimension. Here is another approach."
},
{
"code": null,
"e": 3811,
"s": 3717,
"text": "Now that we have our merged Dataset we can easily perform statistics across ensemble members."
},
{
"code": null,
"e": 3853,
"s": 3811,
"text": "ds_merged[‘temperature’].mean(‘ensemble’)"
},
{
"code": null,
"e": 3894,
"s": 3853,
"text": "ds_merged[‘temperature’].var(‘ensemble’)"
},
{
"code": null,
"e": 3951,
"s": 3894,
"text": "If we want to plot just ens1, we can select it like this"
},
{
"code": null,
"e": 3982,
"s": 3951,
"text": "ds_merged.sel(ensemble='ens1')"
},
{
"code": null,
"e": 4160,
"s": 3982,
"text": "Although accessing individual ensemble members is slightly more cumbersome, I think the benefit of being able to perform statistics across the entire ensemble is more important."
},
{
"code": null,
"e": 4316,
"s": 4160,
"text": "In this section, I will describe two methods to generalize this technique. The code I present is merely meant to give you ideas on how to extend this post."
},
{
"code": null,
"e": 4522,
"s": 4316,
"text": "The first approach is to pipe() the function to a Dataset. This is more aptly applied to chaining multiple functions together. However, depending on the situation, you may want to pipe() a single function."
},
{
"code": null,
"e": 4903,
"s": 4522,
"text": "Another option is to extend Xarray by registering an accessor. In practice, this is done by simply adding a class decorator. This approach is appropriate if you are working on a set of special-purpose functions. For example, maybe you’re working on a class of methods for processing ensemble models. The code below shows how to decorate a class that has the var_merger() function."
},
{
"code": null,
"e": 5313,
"s": 4903,
"text": "Keep in mind that once you register an accessor you can not change it. For example, if you run this code in a notebook and then later decide to add another function to the class and re-run it, that new function will not be registered with the accessor. You would first have to restart the kernel for it to take effect. For that reason, registering an accessor is more appropriately placed in the code library."
},
{
"code": null,
"e": 5372,
"s": 5313,
"text": "You can use your new accessor on a Dataset (ds) like this:"
},
{
"code": null,
"e": 5409,
"s": 5372,
"text": "ds_merged = ds.ensemble.var_merger()"
},
{
"code": null,
"e": 5513,
"s": 5409,
"text": "Notice that the name of the class is irrelevant since it is the accessor name we supply to the Dataset."
},
{
"code": null,
"e": 5742,
"s": 5513,
"text": "Hopefully, this tutorial helps you work more efficiently with ensembles. At the time of writing, I was unable to find a one-liner approach to merge variables like this in the documentation as well as their “How do I...” section."
},
{
"code": null,
"e": 5978,
"s": 5742,
"text": "Xarray is extremely powerful and many “how do I...” questions can be solved with existing functions. Having said that, it can be tricky to find the right functions and chain them together in the right way to achieve the desired object."
},
{
"code": null,
"e": 6176,
"s": 5978,
"text": "Please let me know if you have comments/suggestions on ways to improve this post. Also, please let me know if you are aware of a more elegant solution to merging variables onto a common coordinate."
},
{
"code": null,
"e": 6251,
"s": 6176,
"text": "As always, I am happy to help troubleshoot any issues you may come across."
}
]
|
How to plot magnitude spectrum in Matplotlib in Python? | To plot magintude spectrum, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Get random seed value.
Initialize dt for sampling interval and find the sampling frequency.
Create random data points for t.
To generate noise, get nse, r, cnse and s using numpy
Create a figure and a set of subplots, using subplots() method.
Set the title of the plot.
Plot the magnitude spectrum.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
np.random.seed(0)
dt = 0.01 # sampling interval
Fs = 1 / dt # sampling frequency
t = np.arange(0, 10, dt)
# generate noise:
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(4 * np.pi * t) + cnse
fig, axs = plt.subplots()
axs.set_title("Magnitude Spectrum")
axs.magnitude_spectrum(s, Fs=Fs, color='C1')
plt.show() | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "To plot magintude spectrum, we can take the following steps −"
},
{
"code": null,
"e": 1200,
"s": 1124,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1223,
"s": 1200,
"text": "Get random seed value."
},
{
"code": null,
"e": 1292,
"s": 1223,
"text": "Initialize dt for sampling interval and find the sampling frequency."
},
{
"code": null,
"e": 1325,
"s": 1292,
"text": "Create random data points for t."
},
{
"code": null,
"e": 1379,
"s": 1325,
"text": "To generate noise, get nse, r, cnse and s using numpy"
},
{
"code": null,
"e": 1443,
"s": 1379,
"text": "Create a figure and a set of subplots, using subplots() method."
},
{
"code": null,
"e": 1470,
"s": 1443,
"text": "Set the title of the plot."
},
{
"code": null,
"e": 1499,
"s": 1470,
"text": "Plot the magnitude spectrum."
},
{
"code": null,
"e": 1541,
"s": 1499,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2072,
"s": 1541,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nnp.random.seed(0)\n\ndt = 0.01 # sampling interval\nFs = 1 / dt # sampling frequency\nt = np.arange(0, 10, dt)\n\n# generate noise:\nnse = np.random.randn(len(t))\nr = np.exp(-t / 0.05)\ncnse = np.convolve(nse, r) * dt\ncnse = cnse[:len(t)]\ns = 0.1 * np.sin(4 * np.pi * t) + cnse\n\nfig, axs = plt.subplots()\n\naxs.set_title(\"Magnitude Spectrum\")\naxs.magnitude_spectrum(s, Fs=Fs, color='C1')\n\nplt.show()"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.