title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Word and Text Representations in Natural Language Processing | by Arun Jagota | Towards Data Science
Words are fundamental constructs in many natural languages. Characters in these languages are meaningless until arranged to form a word. When this happens, viola, meaning emerges! When words are arranged sequentially, such as in phrases or sentences, even more meaning emerges. Not surprisingly, core NLP operations involve processing words or sequences of words appropriately. (In this post a sequence of words, which we will abbreviate to text, will be a phrase, a sentence, a paragraph, a section, a chapter, or an entire document. For notational simplicity, we will treat punctuation symbols also as words.) Below is an inventory of key operations on text that power many use cases. Text classification: Classify text into one of a predefined set of categories. Text similarity: Score how similar two pieces of text (sentences, paras, ..., entire documents) are.Text clustering: Cluster several texts — such as documents — into groups of similar ones.Keywords extraction: Extract salient keywords from a corpus of text (e.g. documents).Topics discovery: Discover sets of keywords that go together, i.e. topics, from a corpus of text. All these involve operating on words. Some, such as text similarity, involves operating on word sequences. Local Word Representations By Id In this, every distinct word is assigned a unique identifier. As an example, say our lexicon only has 10 words: dog, cat, tiger, elephant, the, black, white, is, big, fast. Below depicts one local encoding of this lexicon. Word dog cat tiger elephant the black white is are andId 0 1 2 3 4 5 6 7 8 9 Now consider the text: the dog and cat are black. This would be represented as the sequence 4 0 9 1 8 5. This representation retains all the information in the text. This is good. On the other hand texts of differing lengths produce sequences of differing lengths, making them hard to compare. In a Vector Space In this representation, each word in the lexicon forms its own dimension in a vector space. So in our example above, our space would have 10 dimensions. A word is represented by the binary vector in which the word’s dimension’s value is 1 and the rest are 0. We will call this vector the word’s indicator vector. Below are two word indicator vectors from our running example. dog → 1000000000black → 0000010000 Okay, now comes the key point. Texts of arbitrary length are also mapped as vectors in this same space. This makes it easy to compare texts of differing lengths. Just compare their vectors using algebraic similarity measures such as cosine similarity or those based on Euclidean distance or others. Text Vectors So how is text, i.e. a sequence of words of arbitrary length, mapped to a vector in this space. There are various possibilities. The simplest one is to add up the indicator vectors of the words that appear in the text and binarize (i.e. truncate positive counts to 1). Below is the vector we would get for our example. the dog and cat are black → 1100110010 This vector just captures which words from the lexicon are in the text and which not. 1 1 0 0 1 1 0 0 1 0dog cat tiger elephant the black white is are and This representation, also known as bag of words, ignores all word order in the text. Sometimes this is actually beneficial. The vector representations of the cat and dog are black and the dog and cat are black are the same. This is good, as the order in which cat and dog appear here is immaterial. Enhanced Versions Term frequency Consider long texts, such as long documents. The frequencies with which various words appear may also be important. For example, consider two 10,000-word documents, one in which hospital is mentioned 200 times and one in which hospital is mentioned only once. The occurrence of hospital in the first document is more significant than in the second one. A text encoding that captures word frequency is simple to obtain. Just add up the indicator vectors of all the word occurrences in the text. Just don’t binarize. TF X IDF In long documents common words such as the, a, of, and will appear frequently. The frequency-based representation will over-represent their importance. We don’t want two documents to be deemed similar merely because they both have lots of occurrences of the in them. Yes, frequency is important, but only of informative words. In our examples, hospital is an informative word whereas the is not. The TF X IDF representation first involves assigning an informativeness score to each word in the lexicon. This score is estimated from a diverse corpus of text such as sentences (or even paragraphs) drawn from different types of documents. The fewer texts a word appears in, the more informative it is. This is why this measure is called “inverse document frequency”. Armed with the IDF scores of the various words, a text’s TF X IDF vector is easily obtained. Run through all the word occurrences in the text. Multiply the indicator vector of each occurrence by the IDF score of its word. Add them all up. This will result in a vector in which a word’s contribution will depend on its frequency in the document adjusted by the word’s informativeness (i.e. IDF) score. Words uncommon in a diverse corpus but frequent in a particular text will be deemed more important in the text. Let’s see an example. Consider the text the dog and cat are black. We saw its term frequency representation earlier: 1100110010. 1 1 0 0 1 1 0 0 1 0dog cat tiger elephant the black white is are and The TF X IDF representation might look more like this. (Don’t take the positive numbers too literally.) 1 1 0 0 0.1 1 0 0 0.1 0dog cat tiger elephant the black white is are and The words the and are have a greatly reduced influence. Local Representations Can’t Capture Word Similarity Local representations are definitely very useful — indeed widely used. That said, they have a limitation that is a barrier to even more widespread use. They are incapable of accounting for word similarity. Consider three sentences: S1: He is a lawyer S2: He is a attorney S3: He is a doctor Since lawyer and attorney are synonyms we can see that S1 and S2 are semantically identical whereas S3 is unrelated to either. The local representations are incapable of making this distinction because lawyer, attorney, and doctor will be three different dimensions. We can alleviate this situation in one of two ways (or a combination). We can augment the local representations with a dictionary of synonyms.We can calculate correlations among dimensions and take these into account in our scoring. We can augment the local representations with a dictionary of synonyms. We can calculate correlations among dimensions and take these into account in our scoring. While dictionary-based approaches are often effective in practice, they cannot deduce more nuanced relationships than those represented explicitly in the dictionaries. As a simple example consider S5: He teaches computer scienceS6: He teaches data scienceS7: He teaches art We’d like to be able to deem S5 and S6 as semantically more similar than S6 and S7. This example is just the tip of the iceberg. Among the millions of words out there, think how many word similarity relationships are buried! Now extend this to proper nouns. As an example, we’d like to capture that canon and cameras are positively related. Correlation analysis of dimensions can alleviate these issues. From a large corpus of documents, such as Wikipedia, broken down further into smaller chunks such as paragraphs, we might be able to deduce that “computer science” and “data science” are positively correlated, whereas “computer science” and “art” are uncorrelated — perhaps even negatively correlated. We won’t describe the myriads of ways correlation analysis can be applied to alleviate these issues. Instead we will focus on an approach that does an alternate encoding of a word, called a distributed representation, which does a form of correlation analysis under-the-hood. Distributed Word Representations A word’s local representation just has a single 1-valued bit — the one that identifies the word. Consequently, the indicator vectors of any two words differ in exactly two bits. (See example below.) That is, all pairs of indicator vectors are equidistant. dog 1000000000Elephant 0001000000 What if it were possible, instead, to map words to vectors in such a way that similar words get mapped to nearby vectors. It is possible, albeit more involved. First, we need a key concept. Context The context of a word is the words that frequently occur near it, such as in the same sentence. Why is this concept useful to us? Because two words having similar contextual representations will be positively related. Take “cat” and “whiskers”. They will have similar contextual representations as they will both co-occur in contexts involving cats. On the other hand “cat” and “Jupiter” will not appear in the same contexts. So by comparing contextual representations, we can infer that the first pair is related whereas the second pair is not. Okay, let’s now formalize this notion. We model a word’s context as a probability distribution over all words in the lexicon. We will call this the word’s context vector. This is a vector in our original local representation space. Unlike an indicator vector, it is distributed. In fact, the indicator vector is a special case, one whose context is the word itself (no more, no less). Example Say our lexicon just has four words cat, whiskers, computer, and laptop. Their indicator vectors are 1000, 0100, 0010, and 0001 respectively. No pair overlaps. By contrast, plausible context vectors of these four words might be as below. word cat whiskers computer laptopcat 0.7 0.3 0 0whiskers 0.3 0.7 0 0computer 0 0 0.7 0.3laptop 0 0 0.3 0.7 We see that the context vectors of cat and whiskers overlap, as do those of computer and laptop. But not those of whiskers and computer. This makes sense. Estimating Context Vectors Now that we understand what a word’s context vector is, how do we estimate it? Having a large corpus of documents helps. Fortunately, such a corpus, for example, Wikipedia, is easily obtained these days. We simply keep track of co-occurrences of other words with the word of interest in the same proximity, say in the same sentence. Say the word cat occurs in 100 sentences. In 5 of these sentences the word dog also appears. The word dog is in cat’s context with probability 5/100. Improving on Context Vectors There is one issue with this approach. Especially common words such as the will appear in most sentences, so will appear in the contexts of unrelated words. For example, cat’s context will include the because in most sentences in which cat appears the also appears. There is a simple way to alleviate this situation. We divide the word’s contextual probability by its overall probability. Formally, this is as follows. Say context-score(u,v) denotes the score we give to v of being in u’s context. To this point we have defined context-score(u,v) as P(v|u). Instead, we can define it as P(v|u)/P(v). Here P(v|u) is the fraction of sentences containing u that also contain v and P(v) is the fraction of all sentences that contain v. Here is an example. Let’s say that the occurs in 75% of all sentences and 80% of the sentences that cat occurs in. So the score of the being in cat’s context is 80/75. Consider whiskers. Let’s say it appears in only 1% of all sentences, but in 25% of those in which cat appears. So the score of whiskers being in cat’s context is 25/1. In short, the score of whiskers being in cat’s context is much higher than that of the’s. As desired. Context Vectors Will Be Sparse The vector space might have millions of dimensions. The context vectors, however, will tend to be sparse or can be made sparse without losing much information. A word’s context will normally only contain a small proportion of the millions of words in the lexicon. Text Vectors This is just as before. Add the vectors of the word occurrences in the text, after adjusting for the IDF scores of the various words. It's important to note that adjusting with the IDF scores is even more important here than in local representations. This is because a common word such as the will have its own (especially wide) context, whose undamped contribution will pollute the text vector. Let’s see an example. Say from a suitable corpus we picked up the following context representations. Word contextbark howl, dog, tree, wood, leash, shrubdog bark, howl, leash, ... Note that bark’s context captures its two word-senses: tree-bark and dog-bark. Now consider the text the bark of the dog. Assume that IDF will significantly reduce the contribution of the two occurrences of the and the one of of to the text vector. In fact to drop clutter, let’s just set these influences to zero. We are left with: bark dog. Adding up the context vectors of the two words will give us something like howl, dog, tree, wood, leash, shrub The words that occur in the contexts of both the words in the text are highlighted in bold. These words will contribute more to the text’s vector. Now imagine that the text was the bark of the labrador. Assume that our corpus is rich enough to capture the context of labrador. This text’s vector will also be similar. This will let us infer that the bark of the dog and the bark of the labrador are quite similar. Advanced Word Context Models In the past decade, a different way of obtaining word context vectors, going by the name word embeddings, has emerged and gained widespread use. Instead of obtaining context vectors via simple statistical analyses, it trains a neural network to learn word embeddings. This is done in an architecture with a hidden layer. Consequently, learning forces the network to learn good latent features of words. Words are embedded in this feature space, not in the original vector space. We will cover this approach in detail in a separate post, as its description, which involves neural network details, is fairly involved.
[ { "code": null, "e": 450, "s": 172, "text": "Words are fundamental constructs in many natural languages. Characters in these languages are meaningless until arranged to form a word. When this happens, viola, meaning emerges! When words are arranged sequentially, such as in phrases or sentences, even...
Deep Learning: Solving Problems With TensorFlow | by Victor Roman | Towards Data Science
The goal of this article is to define and solve pratical use cases with TensorFlow. To do so, we will solve: An optimization problem A linear regression problem, where we will adjust a regression line to a dataset And we will end solving the “Hello World” of Deep Learning classification projects with the MINST Dataset. Netflix has decided to place one of their famous posters in a building. The marketing team has decided that the advertising poster has to cover an area of 600 square meters, with a margin of 2 meters above and below and 4 meters left and right. However, they have not been informed of the dimensions of the building’s facade. We could send an email to the owner and ask him, but as we know mathematics we can solve it easily. How can we find out the dimensions of the building? The total area of the building is: Width = 4 + x + 4 = x +8 Height = 2 + y + 2 = y +4 Area = Width x Height = (x + 8)*(y + 4) And there is the constraint of: x*y = 600 This allows us to write an equation system: xy = 600 → x = 600/y S(y) = (600/y + 8)(y + 4) = 600 +8y +4*600/y +32 = 632 + 8y + 2400/y In an optimization problem, the information of the slope of the function, (the derivative) is used to calculate its minimum. We have to equal the first derivative to 0 and then check that the second derivative is positive. So, in this case: S’(y) = 8–2400/y2 S’’(y) = 4800/y3 S’(y) = 0 → 0 = 8–2400/y2 → 8 = 2400/y2 → y2 = 2400/8 = 300 → y = sqrt(300) = sqrt(100–3) = sqrt(100)-sqrt(3) = 10-sqrt(3) = 17.32 (we discard the negative sign because it has no physical meaning) Substituting in x: x = 600 / 10-sqrt(3) = 60 / sqrt(3) = 60-sqrt(3) / sqrt(3)-sqrt(3) = 60-sqrt(3) / 3 = 20-sqrt(3) = 34.64 As for y = 17.32 -> S’’(y) = 0.9238 > 0, we have found the minimum solution. Therefore, the dimensions of the building are: Width: x + 8 = 42.64 m Height: y + 4 = 21.32 m Have you seen how useful derivatives are? We just solved this problem analytically. We have been able to solve it because it was a simple problem, but there are many problems for which it is very computationally expensive to solve them analytically, so we use numerical methods. One of these methods is Gradient Descent. What do you say if we solve this problem this time numerically with Tensorflow? Let’s go! import numpy as npimport tensorflow as tfx = tf.Variable(initial_value=tf.random_uniform([1], 34, 35),name=’x’)y = tf.Variable(initial_value=tf.random_uniform([1], 0., 50.), name=’y’)# Loss functions = tf.add(tf.add(632.0, tf.multiply(8.0, y)), tf.divide(2400.0, y), ‘s’)opt = tf.train.GradientDescentOptimizer(0.05)train = opt.minimize(s)sess = tf.Session()init = tf.initialize_all_variables()sess.run(init)old_solution = 0tolerance = 1e-4for step in range(500): sess.run(train) solution = sess.run(y) if np.abs(solution — old_solution) < tolerance: print(“The solution is y = {}”.format(old_solution)) break old_solution = solution if step % 10 == 0: print(step, “y = “ + str(old_solution), “s = “ + str(sess.run(s))) We have managed to calculate y using the gradient descent algorithm. Of course, we now need to calculate x substituting x = 600/y. x = 600/old_solution[0]print(x) Which matches our results, so it seems to work! Let’s plot the results: import matplotlib.pyplot as plty = np.linspace(0, 400., 500)s = 632.0 + 8*y + 2400/yplt.plot(y, s) print("The function minimum is in {}".format(np.min(s)))min_s = np.min(s)s_min_idx = np.nonzero(s==min_s)y_min = y[s_min_idx]print("The y value that reaches the minimum is {}".format(y_min[0])) In this case, we want to find the minimum of the y = log2(x) function. x = tf.Variable(15, name='x', dtype=tf.float32)log_x = tf.log(x)log_x_squared = tf.square(log_x)optimizer = tf.train.GradientDescentOptimizer(0.5)train = optimizer.minimize(log_x_squared)init = tf.initialize_all_variables()def optimize(): with tf.Session() as session: session.run(init) print("starting at", "x:", session.run(x), "log(x)^2:", session.run(log_x_squared)) for step in range(100): session.run(train) print("step", step, "x:", session.run(x), "log(x)^2:", session.run(log_x_squared)) optimize() Let’s plot it! x_values = np.linspace(0,10,100)fx = np.log(x_values)**2plt.plot(x_values, fx)print("The function minimum is in {}".format(np.min(fx)))min_fx = np.min(fx)fx_min_idx = np.nonzero(fx==min_fx)x_min_value = x_values[fx_min_idx]print("The y value that reaches the minimum is {}".format(x_min_value[0])) Let’s see how to adjust a straight line to a dataset that represent the intelligence of every character in the Simpson’s show, from Ralph Wigum to Doctor Frink. Let’s plot the distribution of intelligence against the age, normalized from 0 to 1, where Maggie is the youngest and Montgomery Burns the oldest: n_observations = 50_, ax = plt.subplots(1, 1)xs = np.linspace(0., 1., n_observations)ys = 100 * np.sin(xs) + np.random.uniform(0., 50., n_observations)ax.scatter(xs, ys)plt.draw() Now, we need two tf.placeholders, one to the entry and other to the exit of our regression algorithm. Placeholders are variables that do not need to be assigned a value until the network is executed. X = tf.placeholder(tf.float32)Y = tf.placeholder(tf.float32) Let’s try to optimizie a straight line of linear regression. We need two variables, the weights (W) and the bias (b). Elements of the type tf.Variable need an initialization and its type cannot be changed after being declared. What we can change is its value, by the “assign” method. W = tf.Variable(tf.random_normal([1]), name='weight')b = tf.Variable(tf.random_normal([1]), name='bias')Y_pred = tf.add(tf.multiply(X, W), b) Let’s define now the cost function as the difference between our predictions and the real values. loss = tf.reduce_mean(tf.pow(Y_pred - y, 2)) We’ll define now the optimization method, we will use the gradient descent. Basically, it calculates the variation of each weight with respect to the total error, and updates each weight so that the total error decreases in subsequent iterations. The learning rate indicates how abruptly the weights are updated. learning_rate = 0.01optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)# Definition of the number of iterations and start the initialization using the GPUn_epochs = 1000with tf.Session() as sess: with tf.device("/GPU:0"): # We initialize now all the defined variables sess.run(tf.global_variables_initializer()) # Start the adjust prev_training_loss = 0.0 for epoch_i in range(n_epochs): for (x, y) in zip(xs, ys): sess.run(optimizer, feed_dict={X: x, Y: y}) W_, b_, training_loss = sess.run([W, b, loss], feed_dict={X: xs, Y: ys}) # We print the losses every 20 epochs if epoch_i % 20 == 0: print(training_loss) # Ending conditions if np.abs(prev_training_loss - training_loss) < 0.000001: print(W_, b_) break prev_training_loss = training_loss # Plot of the result plt.scatter(xs, ys) plt.plot(xs, Y_pred.eval(feed_dict={X: xs}, session=sess)) And we have it! With this regression line we will be able to predict the intelligence of every Simpson’s character knowing the age. Let’s see now how to classify digits images with a logistic regression. We will use the “Hello world” of the Deep Learning datasets. Let’s import the relevant libraries and the dataset MNIST: import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data We load the dataset by encoding the labels with one-hot encoding (it converts each label into a vector of length = N_CLASSES, with all 0s except for the index that indicates the class to which the image belongs, which contains a 1). For example, if we have 10 classes (numbers from 0 to 9), and the label belongs to number 5: label = [0 0 0 0 1 0 0 0 0]. mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)print("Train examples: {}".format(mnist.train.num_examples))print("Test examples: {}".format(mnist.test.num_examples))print("Validation examples: {}".format(mnist.validation.num_examples))# Images are stored in a 2D tensor: images_number x image_pixels_vector# Labels are stored in a 2D tensor: images_number x classes_number (one-hot)print("Images Size train: {}".format(mnist.train.images.shape))print("Images Size train: {}".format(mnist.train.labels.shape))# To see the range of the images valuesprint("Min value: {}".format(np.min(mnist.train.images)))print("Max value: {}".format(np.max(mnist.train.images)))# To see some images we will acess a vector of the dataset and resize it to 28x28plt.subplot(131)plt.imshow(np.reshape(mnist.train.images[0, :], (28, 28)), cmap='gray')plt.subplot(132)plt.imshow(np.reshape(mnist.train.images[27500, :], (28, 28)), cmap='gray')plt.subplot(133)plt.imshow(np.reshape(mnist.train.images[54999, :], (28, 28)), cmap='gray') We have already seen a little of what the MNIST dataset consists of. Now, let’s create our regressor: First, we create the placeholder for our input data. In this case, the input is going to be a set of vectors of size 768 (we are going to pass several images at once to our regressor, this way, when it calculates the gradient it will be swept in several images, so the estimation will be more precise than if it used only one) n_input = 784 # Number of data features: number of pixels of the imagen_output = 10 # Number of classes: from 0 to 9net_input = tf.placeholder(tf.float32, [None, n_input]) # We create the placeholder Let’s define now the regression equation: y = W*x + b W = tf.Variable(tf.zeros([n_input, n_output]))b = tf.Variable(tf.zeros([n_output])) As the output is multiclass, we need a function that returns the probabilities of an image belonging to each of the possible classes. For example, if we put an image with a 5, a possible output would be: [0.05 0.05 0.05 0.05 0.55 0.05 0.05 0.05 0.05] whose sum of probabilities is 1, and the class with the highest probability is 5. We apply the softmax function to normalize the output probabilities: net_output = tf.nn.softmax(tf.matmul(net_input, W) + b) # We also need a placeholder for the image label, with which we will compare our prediction And finally, we define our loss function: cross entropyy_true = tf.placeholder(tf.float32, [None, n_output])# We check if our prediction matches the labelcross_entropy = -tf.reduce_sum(y_true * tf.log(net_output))idx_prediction = tf.argmax(net_output, 1)idx_label = tf.argmax(y_true, 1)correct_prediction = tf.equal(idx_prediction, idx_label)# We define our measure of accuracy as the number of hits in relation to the number of predicted samplesaccuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))# We now indicate that we want to minimize our loss function (the cross entropy) by using the gradient descent algorithm and with a rate of learning = 0.01.optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) Everything is now set up! Let’s execute the graph: from IPython.display import clear_outputwith tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Let's train the regressor batch_size = 10 for sample_i in range(mnist.train.num_examples): sample_x, sample_y = mnist.train.next_batch(batch_size) sess.run(optimizer, feed_dict={net_input: sample_x, y_true: sample_y}) # Let's check how is performing the regressor if sample_i < 50 or sample_i % 200 == 0: val_acc = sess.run(accuracy, feed_dict={net_input: mnist.validation.images, y_true: mnist.validation.labels}) print("({}/{}) Acc: {}".format(sample_i, mnist.train.num_examples, val_acc))# Let's show the final accuracy print('Teste accuracy: ', sess.run(accuracy, feed_dict={net_input: mnist.test.images, y_true: mnist.test.labels})) We have just trained our first NEURONAL NETWORK with TensorFlow! Think a little bit about what we just did. We have implemented a logistic regression, with this formula: y = G(Wx + b), where G = softmax() instead of the typical G = sigmoid(). If you look at the following image, which defines the perceptron (a single-layer neural network) you can see as output = Activation_function(Wx). You see? Only the bias is missing! And notice that the input is a 1? So the weight w0 is not multiplied by anything. Exactly! The weight w0 is the bias, which appears with this notation simply to be able to implement it as a matrix multiplication. So, what we have just implemented is a perceptron, with batch_size = 10 1 epoch descent gradient as optimizer and softmax as activation function. As always, I hope you enjoyed the post, that you have learned how to use TensorFlow to solve linear problems and that you have succesfully trained your first Neural Network! If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here . If you want to learn more about Machine Learning and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
[ { "code": null, "e": 281, "s": 172, "text": "The goal of this article is to define and solve pratical use cases with TensorFlow. To do so, we will solve:" }, { "code": null, "e": 305, "s": 281, "text": "An optimization problem" }, { "code": null, "e": 386, "s": 30...
Java | Constructors | Question 3 - GeeksforGeeks
28 Jun, 2021 Which of the following is/are true about constructors in Java? 1) Constructor name should be same as class name. 2) If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. 3) The default constructor calls super() and initializes all instance variables to default value like 0, null. 4) If we want to parent class constructor, it must be called in first line of constructor. (A) 1(B) 1, 2(C) 1, 2 and 3(D) 1, 2, 3 and 4Answer: (D)Explanation:Quiz of this Question Constructors Java-Constructors Java Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Functions | Question 1 Java | Exception Handling | Question 2 Java | Class and Object | Question 1 Java | final keyword | Question 1 Java | Abstract Class and Interface | Question 2 Java | Exception Handling | Question 3 Java | Exception Handling | Question 4 Java | Exception Handling | Question 7 Java | Exception Handling | Question 8 Java | Inheritance | Question 8
[ { "code": null, "e": 25943, "s": 25915, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26006, "s": 25943, "text": "Which of the following is/are true about constructors in Java?" }, { "code": null, "e": 26405, "s": 26006, "text": "\n1) Constructor name shoul...
Ruby | Data Types - GeeksforGeeks
31 Jan, 2019 Data types in Ruby represents different types of data like text, string, numbers, etc. All data types are based on classes because it is a pure Object-Oriented language. There are different data types in Ruby as follows: Numbers Boolean Strings Hashes Arrays Symbols Numbers: Generally a number is defined as a series of digits, using a dot as a decimal mark. Optionally the user can use the underscore as a separator. There are different kinds of numbers like integers and float. Ruby can handle both Integers and floating point numbers. According to their size, there are two types of integers, one is Bignum and second is Fixnum. Example:# Ruby program to illustrate the# Numbers Data Type # float typedistance = 0.1 # both integer and float typetime = 9.87 / 3600speed = distance / timeputs "The average speed of a sprinter is #{speed} km/h"Output:The average speed of a sprinter is 36.474164133738604 km/h # Ruby program to illustrate the# Numbers Data Type # float typedistance = 0.1 # both integer and float typetime = 9.87 / 3600speed = distance / timeputs "The average speed of a sprinter is #{speed} km/h" Output: The average speed of a sprinter is 36.474164133738604 km/h Boolean: Boolean data type represents only one bit of information either true or false. Example:# Ruby program to illustrate the# Boolean Data Type if true puts "It is True!"else puts "It is False!"end if nil puts "nil is True!"else puts "nil is False!"end if 0 puts "0 is True!"else puts "0 is False!"endOutput:It is True! nil is False! 0 is True! # Ruby program to illustrate the# Boolean Data Type if true puts "It is True!"else puts "It is False!"end if nil puts "nil is True!"else puts "nil is False!"end if 0 puts "0 is True!"else puts "0 is False!"end Output: It is True! nil is False! 0 is True! Strings: A string is a group of letters that represent a sentence or a word. Strings are defined by enclosing a text within a single (”) or double (“”) quotes. You can use both double quotes and single quotes to create strings. Strings are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings doesn’t allow substitution and allow backslash notation only for \\ and \’. Example:# Ruby program to illustrate the# Strings Data Type #!/usr/bin/ruby -wputs "String Data Type";puts 'escape using "\\"';puts 'That\'s right';Output:String Data Type escape using "\" That's right # Ruby program to illustrate the# Strings Data Type #!/usr/bin/ruby -wputs "String Data Type";puts 'escape using "\\"';puts 'That\'s right'; Output: String Data Type escape using "\" That's right Hashes: A hash assign its values to its key. Value to a key is assigned by => sign. A key pair is separated with a comma between them and all the pairs are enclosed within curly braces. A hash in Ruby is like an object literal in JavaScript or an associative array in PHP. They’re made similarly to arrays.e. A trailing comma is ignored. Example:# Ruby program to illustrate the# Hashes Data Type #!/usr/bin/rubyhsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }hsh.each do |key, value| print key, " is ", value, "\n"endOutput:red is 3840 green is 240 blue is 15 # Ruby program to illustrate the# Hashes Data Type #!/usr/bin/rubyhsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }hsh.each do |key, value| print key, " is ", value, "\n"end Output: red is 3840 green is 240 blue is 15 Arrays: An array stores data or list of data. It can contain all types of data. Data in an array are separated by comma in between them and are enclosed within square bracket.The position of elements in an array starts with 0. A trailing comma is ignored. Example:# Ruby program to illustrate the# Arrays Data Type #!/usr/bin/rubyary = [ "fred", 10, 3.14, "This is a string", "last element", ]ary.each do |i| puts iendOutput:fred 10 3.14 This is a string last element # Ruby program to illustrate the# Arrays Data Type #!/usr/bin/rubyary = [ "fred", 10, 3.14, "This is a string", "last element", ]ary.each do |i| puts iend Output: fred 10 3.14 This is a string last element Symbols: Symbols are light-weight strings. A symbol is preceded by a colon (:). They are used instead of strings because they can take up much less memory. Symbols have better performance. Example:# Ruby program to illustrate the# Symbols Data Type #!/usr/bin/rubydomains = {:sk => "GeeksforGeeks", :no => "GFG", :hu => "Geeks"} puts domains[:sk]puts domains[:no]puts domains[:hu]Output:GeeksforGeeks GFG Geeks # Ruby program to illustrate the# Symbols Data Type #!/usr/bin/rubydomains = {:sk => "GeeksforGeeks", :no => "GFG", :hu => "Geeks"} puts domains[:sk]puts domains[:no]puts domains[:hu] Output: GeeksforGeeks GFG Geeks somilsinghal2019 Ruby-Basics Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Array slice() function Ruby | Array count() operation Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Numeric round() function Ruby | String capitalize() Method
[ { "code": null, "e": 25024, "s": 24996, "text": "\n31 Jan, 2019" }, { "code": null, "e": 25245, "s": 25024, "text": "Data types in Ruby represents different types of data like text, string, numbers, etc. All data types are based on classes because it is a pure Object-Oriented lan...
HTML | list Attribute - GeeksforGeeks
21 Jan, 2022 The list attribute in HTML is used to identify a list of pre-defined options for an <input> element to suggest the user.Usage: This attribute is used by the <input> element. Syntax: <input list="name"> Where, name is a string that will work as id and will be used to link the <input> element with the <datalist> element.Below programs illustrate the list attribute: Attribute Values: datalist_id: It is used to specify the Id of the datalist that will used to make a link up with the input element.Program 1: html <!DOCTYPE html><html> <head> <title>HTML list Attribute</title> </head> <body> <h1 style = "color:green">HTML list Attribute</h1> <form action=""> <label>Your Cars Name: </label> <input list="cars"> <datalist id="cars"> <option value="BMW"/> <option value="Bentley"/> <option value="Mercedes"/> <option value="Audi"/> <option value="Volkswagen"/> </datalist> </form> </body></html> Output: Program 2: html <!DOCTYPE html><html> <head> <title>HTML | list Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green">HTML list Attribute</h1> <form action=""> <label>Your Cars Name: </label> <input list="cars" id="carsInput"> <datalist id="cars"> <option value="BMW"/> <option value="Bentley"/> <option value="Mercedes"/> <option value="Audi"/> <option value="Volkswagen"/> </datalist> <button onclick="geek()" type="button"> Click Here </button> </form> <p id="output"></p> <script type="text/javascript"> function geek(){ var o1 = document.getElementById("carsInput").value; document.getElementById("output").innerHTML = "You select " + o1 + " option"; } </script> </body></html> Output: Before clicking the button: After clicking the button: Supported Browsers: The browser supported by list attribute are listed below: Google Chrome 20.0 Internet Explorer 10.0 Firefox 4.0 Opera 9.6 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 ManasChhabra2 HTML-Attributes 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 set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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": 24954, "s": 24926, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25128, "s": 24954, "text": "The list attribute in HTML is used to identify a list of pre-defined options for an <input> element to suggest the user.Usage: This attribute is used by the <input...
Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks
12 Jan, 2022 Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. If a Greedy Algorithm can solve a problem, then it generally becomes the best method to solve that problem as the Greedy algorithms are in general more efficient than other techniques like Dynamic Programming. But Greedy algorithms cannot always be applied. For example, the Fractional Knapsack problem can be solved using Greedy, but 0-1 Knapsack cannot be solved using Greedy.Following are some standard algorithms that are Greedy algorithms. 1) Kruskal’s Minimum Spanning Tree (MST): In Kruskal’s algorithm, we create a MST by picking edges one by one. The Greedy Choice is to pick the smallest weight edge that doesn’t cause a cycle in the MST constructed so far. 2) Prim’s Minimum Spanning Tree: In Prim’s algorithm also, we create a MST by picking edges one by one. We maintain two sets: a set of the vertices already included in MST and the set of the vertices not yet included. The Greedy Choice is to pick the smallest weight edge that connects the two sets. 3) Dijkstra’s Shortest Path: Dijkstra’s algorithm is very similar to Prim’s algorithm. The shortest-path tree is built up, edge by edge. We maintain two sets: a set of the vertices already included in the tree and the set of the vertices not yet included. The Greedy Choice is to pick the edge that connects the two sets and is on the smallest weight path from source to the set that contains not yet included vertices. 4) Huffman Coding: Huffman Coding is a loss-less compression technique. It assigns variable-length bit codes to different characters. The Greedy Choice is to assign the least bit length code to the most frequent character.The greedy algorithms are sometimes also used to get an approximation for Hard optimization problems. For example, Traveling Salesman Problem is an NP-Hard problem. A Greedy choice for this problem is to pick the nearest unvisited city from the current city at every step. These solutions don’t always produce the best optimal solution but can be used to get an approximately optimal solution.Let us consider the Activity Selection problem as our first example of Greedy algorithms. Following is the problem statement. You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example: Example 1 : Consider the following 3 activities sorted by by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person can perform at most two activities. The maximum set of activities that can be executed is {0, 2} [ These are indexes in start[] and finish[] ] Example 2 : Consider the following 6 activities sorted by by finish time. start[] = {1, 3, 0, 5, 8, 5}; finish[] = {2, 4, 6, 7, 9, 9}; A person can perform at most four activities. The maximum set of activities that can be executed is {0, 1, 3, 4} [ These are indexes in start[] and finish[] ] The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of the previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.1) Sort the activities according to their finishing time 2) Select the first activity from the sorted array and print it. 3) Do the following for the remaining activities in the sorted array. .......a) If the start time of this activity is greater than or equal to the finish time of the previously selected activity then select this activity and print it.In the following C implementation, it is assumed that the activities are already sorted according to their finish time. C++ C Java C# Python3 PHP Javascript // C++ program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include <bits/stdc++.h>using namespace std; // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; cout <<"Following activities are selected "<< endl; // The first activity always gets selected i = 0; cout <<" "<< i; // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { cout <<" " << j; i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;}//this code contributed by shivanisinghss2110 // C program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include<stdio.h> // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; printf ("Following activities are selected n"); // The first activity always gets selected i = 0; printf("%d ", i); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { printf ("%d ", j); i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;} // The following implementation assumes that the activities// are already sorted according to their finish timeimport java.util.*;import java.lang.*;import java.io.*; class ActivitySelection{ // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities public static void printMaxActivities(int s[], int f[], int n) { int i, j; System.out.print("Following activities are selected : n"); // The first activity always gets selected i = 0; System.out.print(i+" "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { System.out.print(j+" "); i = j; } } } // driver program to test above function public static void main(String[] args) { int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = s.length; printMaxActivities(s, f, n); } } // The following implementation assumes// that the activities are already sorted// according to their finish timeusing System; class GFG{// Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiespublic static void printMaxActivities(int[] s, int[] f, int n){int i, j; Console.Write("Following activities are selected : "); // The first activity always gets selectedi = 0;Console.Write(i + " "); // Consider rest of the activitiesfor (j = 1; j < n; j++){ // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { Console.Write(j + " "); i = j; }}} // Driver Codepublic static void Main(){ int[] s = {1, 3, 0, 5, 8, 5}; int[] f = {2, 4, 6, 7, 9, 9}; int n = s.Length; printMaxActivities(s, f, n);}} // This code is contributed// by ChitraNayal """The following implementation assumes that the activitiesare already sorted according to their finish time""" """Prints a maximum set of activities that can be done by asingle person, one at a time"""# n --> Total number of activities# s[]--> An array that contains start time of all activities# f[] --> An array that contains finish time of all activities def printMaxActivities(s , f ): n = len(f) print ("The following activities are selected") # The first activity is always selected i = 0 print (i,end=' ') # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if s[j] >= f[i]: print (j,end=' ') i = j # Driver program to test above functions = [1 , 3 , 0 , 5 , 8 , 5]f = [2 , 4 , 6 , 7 , 9 , 9]printMaxActivities(s , f) # This code is contributed by Nikhil Kumar Singh <?php// PHP program for activity selection problem.// The following implementation assumes that// the activities are already sorted according// to their finish time // Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiesfunction printMaxActivities($s, $f, $n){ echo "Following activities are selected " . "\n"; // The first activity always gets selected $i = 0; echo $i . " "; // Consider rest of the activities for ($j = 1; $j < $n; $j++) { // If this activity has start time greater // than or equal to the finish time of // previously selected activity, then select it if ($s[$j] >= $f[$i]) { echo $j . " "; $i = $j; } }} // Driver Code$s = array(1, 3, 0, 5, 8, 5);$f = array(2, 4, 6, 7, 9, 9);$n = sizeof($s);printMaxActivities($s, $f, $n); // This code is contributed// by Akanksha Rai?> <script>// The following implementation assumes that the activities// are already sorted according to their finish time // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities function printMaxActivities(s,f,n) { let i, j; document.write("Following activities are selected : n"); // The first activity always gets selected i = 0; document.write(i+" "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { document.write(j+" "); i = j; } } } // Driver program to test above function let s = [1, 3, 0, 5, 8, 5] let f = [2, 4, 6, 7, 9, 9] let n = s.length; printMaxActivities(s, f, n); // This code is contributed by avanitrachhadiya2155</script> Following activities are selected n0 1 3 4 How does Greedy Choice work for Activities sorted according to finish time? Let the given set of activities be S = {1, 2, 3, ...n} and activities are sorted by finish time. The greedy choice is to always pick activity 1. How come activity 1 always provides one of the optimal solutions. We can prove it by showing that if there is another solution B with the first activity other than 1, then there is also a solution A of the same size with activity 1 as the first activity. Let the first activity selected by B be k, then there always exist A = {B – {k}} U {1}. (Note that the activities in B are independent and k has the smallest finishing time among all. Since k is not 1, finish(k) >= finish(1)). How to implement when given activities are not sorted? We create a structure/class for activities. We sort all activities by finish time (Refer sort in C++ STL). Once we have activities sorted, we apply the same algorithm.Below image is an illustration of the above approach: Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; // A job has a start time, finish time and profit.struct Activitiy{ int start, finish;}; // A utility function that is used for sorting// activities according to finish timebool activityCompare(Activitiy s1, Activitiy s2){ return (s1.finish < s2.finish);} // Returns count of the maximum set of activities that can// be done by a single person, one at a time.void printMaxActivities(Activitiy arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, activityCompare); cout << "Following activities are selected n"; // The first activity always gets selected int i = 0; cout << "(" << arr[i].start << ", " << arr[i].finish << "), "; // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (arr[j].start >= arr[i].finish) { cout << "(" << arr[j].start << ", " << arr[j].finish << "), "; i = j; } }} // Driver programint main(){ Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}}; int n = sizeof(arr)/sizeof(arr[0]); printMaxActivities(arr, n); return 0;} // Java program for activity selection problem// when input activities may not be sorted.import java.io.*;import java.util.*; // A job has a start time, finish time and profit.class Activity{ int start, finish; // Constructor public Activity(int start, int finish) { this.start = start; this.finish = finish; }} // class to define user defined comparatorclass Compare{ // A utility function that is used for sorting // activities according to finish time static void compare(Activity arr[], int n) { Arrays.sort(arr, new Comparator<Activity>() { @Override public int compare(Activity s1, Activity s2) { return s1.finish - s2.finish; } }); }} // Driver classclass GFG { // Returns count of the maximum set of activities that // can // be done by a single person, one at a time. static void printMaxActivities(Activity arr[], int n) { // Sort jobs according to finish time Compare obj = new Compare(); obj.compare(arr, n); System.out.println( "Following activities are selected :"); // The first activity always gets selected int i = 0; System.out.print("(" + arr[i].start + ", " + arr[i].finish + "), "); // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than // or equal to the finish time of previously // selected activity, then select it if (arr[j].start >= arr[i].finish) { System.out.print("(" + arr[j].start + ", " + arr[j].finish + "), "); i = j; } } } // Driver code public static void main(String[] args) { int n = 6; Activity arr[] = new Activity[n]; arr[0] = new Activity(5, 9); arr[1] = new Activity(1, 2); arr[2] = new Activity(3, 4); arr[3] = new Activity(0, 6); arr[4] = new Activity(5, 7); arr[5] = new Activity(8, 9); printMaxActivities(arr, n); }} // This code is contributed by Dharanendra L V. ''' Python program for activity selection problem when input activities may not be sorted.'''def MaxActivities(arr, n): selected = [] # Sort jobs according to finish time Activity.sort(key = lambda x : x[1]) # The first activity always gets selected i = 0 selected.append(arr[i]) for j in range(1, n): '''If this activity has start time greater than or equal to the finish time of previously selected activity, then select it''' if arr[j][0] >= arr[i][1]: selected.append(arr[j]) i = j return selected # Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]]n = len(Activity)selected = MaxActivities(Activity, n)print("Following activities are selected :")print(selected) # This cde is contributed by kshitijjainm <script>/* JavaScript program for activity selection problem when input activities may not be sorted.*/function MaxActivities(arr, n){ let selected = []; // Sort jobs according to finish time Activity = Activity.sort(function(a,b) { return a[1] - b[1]; }); // The first activity always gets selected let i = 0 selected.push(arr[i]); for(let j=1;j<n;j++){ /*If this activity has start time greater than or equal to the finish time of previously selected activity, then select it*/ if( arr[j][0] >= arr[i][1]){ selected.push(arr[j]); i = j; } } return selected;}// Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]];n = Activity.length;selected = MaxActivities(Activity, n);document.write("Following activities are selected : <br>")console.log(selected)for(let i = 0;i<selected.length;i++) document.write("("+selected[i]+"), ")</script> Output: Following activities are selected (1, 2), (3, 4), (5, 7), (8, 9), Time Complexity: It takes O(n log n) time if input activities may not be sorted. It takes O(n) time when it is given that input activities are always sorted.Using STL we can solve it as follows: CPP Java Javascript // C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; void SelectActivities(vector<int>s,vector<int>f){// Vector to store results. vector<pair<int,int>>ans; // Minimum Priority Queue to sort activities in ascending order of finishing time (f[i]). priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>p; for(int i=0;i<s.size();i++){ // Pushing elements in priority queue where the key is f[i] p.push(make_pair(f[i],s[i])); } auto it = p.top(); int start = it.second; int end = it.first; p.pop(); ans.push_back(make_pair(start,end)); while(!p.empty()){ auto itr = p.top(); p.pop(); if(itr.second >= end){ start = itr.second; end = itr.first; ans.push_back(make_pair(start,end)); } } cout << "Following Activities should be selected. " << endl << endl; for(auto itr=ans.begin();itr!=ans.end();itr++){ cout << "Activity started at: " << (*itr).first << " and ends at " << (*itr).second << endl; }} // Driver programint main(){ vector<int>s = {1, 3, 0, 5, 8, 5}; vector<int>f = {2, 4, 6, 7, 9, 9}; SelectActivities(s,f); return 0;} // java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Pair class static class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } static void SelectActivities(int s[], int f[]) { // Vector to store results. ArrayList<Pair> ans = new ArrayList<>(); // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). PriorityQueue<Pair> p = new PriorityQueue<>( (p1, p2) -> p1.first - p2.first); for (int i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.add(new Pair(f[i], s[i])); } Pair it = p.poll(); int start = it.second; int end = it.first; ans.add(new Pair(start, end)); while (!p.isEmpty()) { Pair itr = p.poll(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.add(new Pair(start, end)); } } System.out.println( "Following Activities should be selected. \n"); for (Pair itr : ans) { System.out.println( "Activity started at: " + itr.first + " and ends at " + itr.second); } } // Driver Code public static void main(String[] args) { int s[] = { 1, 3, 0, 5, 8, 5 }; int f[] = { 2, 4, 6, 7, 9, 9 }; // Function call SelectActivities(s, f); }} // This code is contributed by Kingash. <script>// javascript program for the above approach // Pair classclass Pair{ constructor(first,second) { this.first = first; this.second = second; }} function SelectActivities(s,f){ // Vector to store results. let ans = []; // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). let p = []; for (let i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.push(new Pair(f[i], s[i])); } p.sort(function(a,b){return a.first-b.first;}); let it = p.shift(); let start = it.second; let end = it.first; ans.push(new Pair(start, end)); while (p.length!=0) { let itr = p.shift(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.push(new Pair(start, end)); } } document.write( "Following Activities should be selected. <br>"); for(let itr of ans.values()) { document.write( "Activity started at: " + itr.first + " and ends at " + itr.second+"<br>"); }} // Driver Codelet s=[1, 3, 0, 5, 8, 5 ];let f=[2, 4, 6, 7, 9, 9 ];// Function callSelectActivities(s, f); // This code is contributed by rag2127</script> Following Activities should be selected. Activity started at: 1 and ends at 2 Activity started at: 3 and ends at 4 Activity started at: 5 and ends at 7 Activity started at: 8 and ends at 9 ukasp Akanksha_Rai zafir_ahmad kshitijjainm shivanisinghss2110 dharanendralv23 Kingash avanitrachhadiya2155 rohitsingh07052 rag2127 surajv tejaskanikdaley1996 amartyaghoshgfg Activity Selection Problem Amazon Facebook Flipkart MakeMyTrip Morgan Stanley Visa Greedy Flipkart Morgan Stanley Amazon MakeMyTrip Visa Facebook Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for array rotation Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Difference between Prim's and Kruskal's algorithm for MST Program for Least Recently Used (LRU) Page Replacement algorithm Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm Minimum Number of Platforms Required for a Railway/Bus Station Graph Coloring | Set 2 (Greedy Algorithm) Program for Page Replacement Algorithms | Set 2 (FIFO) Greedy approach vs Dynamic programming
[ { "code": null, "e": 35839, "s": 35811, "text": "\n12 Jan, 2022" }, { "code": null, "e": 38614, "s": 35839, "text": "Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Gree...
How to Find the Difference Between Two Rows in Pandas? - GeeksforGeeks
19 Dec, 2021 In this article, we are going to see how to find the difference between two rows in Pandas. Pandas DataFrame is a two-dimensional data structure in tabular form with labeled axes. During data analysis, one might need to compute the difference between two rows for comparison purposes. This can be done using pandas.DataFrame.diff() function. This function calculates the difference between two consecutive DataFrame elements. Syntax: pandas.DataFrame.diff(periods=1, axis=0) Parameters: periods: Represents periods to shift for computing difference, Integer type value. Default value is 1 axis: Represents difference to be taken over rown or columns. Can take two values {0: rows, 1: columns}. Default value is 0 Returns: Returns DataFrame Example 1: To test this function we created a dummy DataFrame with 3 columns and 6 rows. Now, this diff function will find the difference of each row with its previous row as periods by default is 1. Hence the reason why values in the 0th indexed row are NaN. Python3 # Importing Pandas Libraryimport pandas as pd # Creating dummy DataFrame for testingdf = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6], 'b': [8, 18, 27, 20, 33, 49], 'c': [2, 24, 6, 16, 20, 52]})# Printing DataFrame before applying diff functionprint(df) # Printing DataFrame after applying diff functionprint("Difference: ")print(df.diff()) Output: a b c 0 1 8 2 1 2 18 24 2 3 27 6 3 4 20 16 4 5 33 20 5 6 49 52 Difference: a b c 0 NaN NaN NaN 1 1.0 10.0 22.0 2 1.0 9.0 -18.0 3 1.0 -7.0 10.0 4 1.0 13.0 4.0 5 1.0 16.0 32.0 Example 2: Python3 # Importing Pandas Libraryimport pandas as pd # Creating dummy DataFrame for testingdf = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6], 'b': [8, 18, 27, 20, 33, 49], 'c': [2, 24, 6, 16, 20, 52]})# Printing DataFrame before applying diff functionprint(df) # Printing DataFrame after applying diff functionprint("Difference: ")print(df.diff(periods=2)) Output: a b c 0 1 8 2 1 2 18 24 2 3 27 6 3 4 20 16 4 5 33 20 5 6 49 52 Difference: a b c 0 NaN NaN NaN 1 NaN NaN NaN 2 2.0 19.0 4.0 3 2.0 2.0 -8.0 4 2.0 6.0 14.0 5 2.0 29.0 36.0 pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25630, "s": 25537, "text": "In this article, we are going to see how to find the difference between two rows in Pandas. " }, { "code": null, "e": 25965, "s": 25630, "text"...
How to italicize text in CSS ? - GeeksforGeeks
04 Jul, 2021 In this article, we will see how to make a text italic using CSS. To italicize text in any webpage the CSS font-style property is used. We have a variety of options to set it to italic text. normal: It is the normal font-style. It is the same as 400, the default numeric value for boldness. bold: It is the bold font-style. It is the same as 700. italic: It is the cursive font-style. Approach: The font-style property in CSS has three values that are normal, italic, and bold. The CSS value italic is used to italicize the text. Syntax: font-style: italic; Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <!--Style CSS--> <style> .gfg { font-style: italic; font-size: 24px; margin: 10px; padding: 2px; color: black; } </style></head> <body> <h2> GeeksForGeeks | A Computer Science Portal for Geeks </h2> <p class="gfg"> This platform has been designed for every geek wishing to expand their knowledge, share their knowledge and is ready to grab their dream job. We have millions of articles, live as well as online courses, thousands of tutorials and much more just for the geek inside you. </p> <p class="geeks"> Thank You for choosing and supporting us! </p></body> </html> Note: When you will be using an external CSS file always use some default CSS for your webpage this default CSS written in * { } selector. This will remove default CSS from your webpage. Output: Now, as you can see in the output, we have created an italicized text in our webpage using CSS, which will attract readers to read the contents on the webpage. CSS-Properties CSS-Questions Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n04 Jul, 2021" }, { "code": null, "e": 26812, "s": 26621, "text": "In this article, we will see how to make a text italic using CSS. To italicize text in any webpage the CSS font-style property is used. We have a variety of option...
Class toString() method in Java with Examples - GeeksforGeeks
27 Nov, 2019 The toString() method of java.lang.Class class is used to convert the instance of this Class to a string representation. This method returns the formed string representation. Syntax: public String toString() Parameter: This method does not accept any parameter. Return Value: This method returns the String representation of this object. Below programs demonstrate the toString() method. Example 1: // Java program to demonstrate toString() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c1 = Class.forName("java.lang.String"); System.out.print("Class represented by c1: "); // toString method on c1 System.out.println(c1.toString()); }} Class represented by c1: class java.lang.String Example 2: // Java program to demonstrate toString() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for the class // with the specified name Class c2 = int.class; Class c3 = void.class; System.out.print("Class represented by c2: "); // toString method on c2 System.out.println(c2.toString()); System.out.print("Class represented by c3: "); // toString method on c3 System.out.println(c3.toString()); }} Class represented by c2: int Class represented by c3: void Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#toString– 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. 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": "\n27 Nov, 2019" }, { "code": null, "e": 25400, "s": 25225, "text": "The toString() method of java.lang.Class class is used to convert the instance of this Class to a string representation. This method returns the formed string repr...
PHP | str_split() Function - GeeksforGeeks
01 Aug, 2021 The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array. Syntax: array str_split($org_string, $splitting_length) Parameters:The function accepts two parameters and are described below: $org_string (mandatory): This refers to the original string that the user needs to split into an array.$splitting_length (optional): This refers to the length of each array element, we wish to split our string into. By default the function accepts the value as 1. $org_string (mandatory): This refers to the original string that the user needs to split into an array. $splitting_length (optional): This refers to the length of each array element, we wish to split our string into. By default the function accepts the value as 1. Return Values: The function returns an array. If the length parameter exceeds the length of the original string, then the whole string is returned as a single element. If the length parameter is less than 1, then False is returned. By default length is equal to 1. Examples: Input: "Hello" Output: Array ( [0] => H [1] => e [2] => l [3] => l [4] => o ) The below program will explain the working of the str_split() function. <?php// PHP program to display the working of str_split() $string = "Geeks"; // Since second argument is not passed,// string is split into substrings of size 1.print_r(str_split($string)); $string = "GeeksforGeeks"; // Splits string into substrings of size 4// and returns array of substrings.print_r(str_split($string, 4))?> Output: Array ( [0] => G [1] => e [2] => e [3] => k [4] => s ) Array ( [0] => Geek [1] => sfor [2] => Geek [3] => s ) Reference:http://php.net/manual/en/function.str-split.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. 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 Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26223, "s": 26195, "text": "\n01 Aug, 2021" }, { "code": null, "e": 26476, "s": 26223, "text": "The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller s...
Wand Drawing() function in Python - GeeksforGeeks
11 May, 2020 Another module for wand is wand.drawing. This module provides us with some very basic drawing functions. wand.drawing.Drawing object buffers instructions for drawing shapes into images, and then it can draw these shapes into zero or more images. Syntax : with Drawing() as draw: Note: In the above syntax “as draw” is just a nomenclature and can be any string as needed. The Drawing function in Python wand take has no parameter. Example #1: # Import important objects from wand libraryfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # Create draw object using Drawing() functionwith Drawing() as draw: with Image(width = 200, height = 200, background = Color('green')) as img: draw(img) img.save(filename ='empty.gif') Output Image: Let’s draw a line Example #2: # Import important objects from wand libraryfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # Create draw object using Drawing() functionwith Drawing() as draw: draw.stroke_color = Color('black') draw.stroke_width = 2 draw.line((5, 5), (45, 50)) with Image(width = 200, height = 200, background = Color('green')) as img: draw.draw(img) img.save(filename ='line.gif') Output Image: Python-gui Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 May, 2020" }, { "code": null, "e": 25783, "s": 25537, "text": "Another module for wand is wand.drawing. This module provides us with some very basic drawing functions. wand.drawing.Drawing object buffers instructions for drawi...
Product of 2 numbers using recursion | Set 2 - GeeksforGeeks
18 Aug, 2021 Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative. Examples: Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15 A recursive solution to the above problem for only positive numbers is already discussed in the previous article. In this post, a recursive solution for finding the product for both positive and negative numbers is discussed. Below is the step by step approach: Check if one or both of the numbers are negative.If the number passed in the second parameter is negative swap the parameters and call the function again.If both of the parameters are negative call the function again and pass the absolute values of the numbers as parameters.If n>m call the function with swapped parameters for less execution time of the function.As long as m is not 0 keep on calling the function with subcase n, m-1 and return n + multrecur(n, m-1). Check if one or both of the numbers are negative. If the number passed in the second parameter is negative swap the parameters and call the function again. If both of the parameters are negative call the function again and pass the absolute values of the numbers as parameters. If n>m call the function with swapped parameters for less execution time of the function. As long as m is not 0 keep on calling the function with subcase n, m-1 and return n + multrecur(n, m-1). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find product of two numbers// using recursion#include <iostream>using namespace std; // Recursive function to calculate the product// of 2 integersint multrecur(int n, int m){ // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // if n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; }}// Driver codeint main(){ cout << "5 * 3 = " << multrecur(5, 3) << endl; cout << "5 * (-3) = " << multrecur(5, -3) << endl; cout << "(-5) * 3 = " << multrecur(-5, 3) << endl; cout << "(-5) * (-3) = " << multrecur(-5, -3) << endl; return 0;} //Java program to find product of two numbers//using recursionpublic class GFG { //Recursive function to calculate the product //of 2 integers static int multrecur(int n, int m) { // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // if n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; } } //Driver code public static void main(String[] args) { System.out.println("5 * 3 = " + multrecur(5, 3)); System.out.println("5 * (-3) = " + multrecur(5, -3)); System.out.println("(-5) * 3 = " + multrecur(-5, 3)); System.out.println("(-5) * (-3) = " +multrecur(-5, -3)); }} # Python 3 program to find product of two numbers# using recursion # Recursive function to calculate the product# of 2 integersdef multrecur(n, m) : # case 1 : n<0 and m>0 # swap the position of n and m to keep second # parameter positive if n > 0 and m < 0 : return multrecur(m,n) # case 2 : both n and m are less than 0 # return the product of their absolute values elif n < 0 and m < 0 : return multrecur((-1 * n),(-1 * m)) # if n>m , swap n and m so that recursion # takes less time if n > m : return multrecur(m, n) # as long as m is not 0 recursively call multrecur for # n and m-1 return sum of n and the product of n times m-1 elif m != 0 : return n + multrecur(n, m-1) # m=0 then return 0 else : return 0 # Driver Codeif __name__ == "__main__" : print("5 * 3 =",multrecur(5, 3)) print("5 * (-3) =",multrecur(5, -3)) print("(-5) * 3 =",multrecur(-5, 3)) print("(-5) * (-3) =",multrecur(-5, -3)) # This code is contributed by ANKITRAI1 // C# program to find product of// two numbers using recursionusing System;class GFG{ // Recursive function to calculate// the product of 2 integersstatic int multrecur(int n, int m){// case 1 : n<0 and m>0// swap the position of n and m// to keep second parameter positiveif (n > 0 && m < 0){ return multrecur(m, n);} // case 2 : both n and m are less than 0// return the product of their absolute valueselse if (n < 0 && m < 0){ return multrecur((-1 * n), (-1 * m));} // if n>m , swap n and m so that// recursion takes less timeif (n > m){ return multrecur(m, n);} // as long as m is not 0 recursively// call multrecur for n and m-1 return// sum of n and the product of n times m-1else if (m != 0){ return n + multrecur(n, m - 1);} // m=0 then return 0else{ return 0;}} // Driver codepublic static void Main(){ Console.WriteLine("5 * 3 = " + multrecur(5, 3)); Console.WriteLine("5 * (-3) = " + multrecur(5, -3)); Console.WriteLine("(-5) * 3 = " + multrecur(-5, 3)); Console.WriteLine("(-5) * (-3) = " + multrecur(-5, -3));}} // This code is contributed by anuj_67 <?php// PHP program to find product of// two numbers using recursion // Recursive function to calculate// the product of 2 integersfunction multrecur($n, $m){ // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if ($n > 0 && $m < 0) { return multrecur($m, $n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if ($n < 0 && $m < 0) { return multrecur((-1 * $n), (-1 * $m)); } // if n>m , swap n and m so that // recursion takes less time if ($n > $m) { return multrecur($m, $n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if ($m != 0) { return $n + multrecur($n, $m - 1); } // m=0 then return 0 else { return 0; }} // Driver codeecho "5 * 3 = " . multrecur(5, 3) . "\n";echo "5 * (-3) = " . multrecur(5, -3) . "\n";echo "(-5) * 3 = " . multrecur(-5, 3) . "\n";echo "(-5) * (-3) = " . multrecur(-5, -3) . "\n"; // This code is contributed by mits?> <script> // Javascript program to find product// of two numbers using recursion // Recursive function to calculate the// product of 2 integersfunction multrecur(n, m){ // case 1 : n<0 and m>0 // Swap the position of n and m to // keep second parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // If n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // As long as m is not 0 recursively // call multrecur for n and m-1 // return sum of n and the product // of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; }} // Driver codedocument.write("5 * 3 = " + multrecur(5, 3) + "<br>");document.write("5 * (-3) = " + multrecur(5, -3) + "<br>");document.write("(-5) * 3 = " + multrecur(-5, 3) + "<br>");document.write("(-5) * (-3) = " + multrecur(-5, -3) + "<br>"); // This code is contributed by rutvik_56 </script> 5 * 3 = 15 5 * (-3) = -15 (-5) * 3 = -15 (-5) * (-3) = 15 Time Complexity: O(max(N, M)) Auxiliary Space: O(max(N, M)) ankthon Mithun Kumar ukasp vt_m rutvik_56 pankajsharmagfg Algorithms C++ Programs Recursion Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 26235, "s": 26207, "text": "\n18 Aug, 2021" }, { "code": null, "e": 26379, "s": 26235, "text": "Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative." }, { "code...
Matrix Exponentiation - GeeksforGeeks
12 Aug, 2021 This is one of the most used techniques in competitive programming. Let us first consider below simple question.What is the minimum time complexity to find n’th Fibonacci Number? We can find n’th Fibonacci Number in O(Log n) time using Matrix Exponentiation. Refer method 4 of this for details. In this post, a general implementation of Matrix Exponentiation is discussed. For solving the matrix exponentiation we are assuming a linear recurrence equation like below: F(n) = a*F(n-1) + b*F(n-2) + c*F(n-3) for n >= 3 . . . . . Equation (1) where a, b and c are constants. For this recurrence relation, it depends on three previous values. Now we will try to represent Equation (1) in terms of the matrix. [First Matrix] = [Second matrix] * [Third Matrix] | F(n) | = Matrix 'C' * | F(n-1) | | F(n-1) | | F(n-2) | | F(n-2) | | F(n-3) | Dimension of the first matrix is 3 x 1 . Dimension of the third matrix is also 3 x 1. So the dimension of the second matrix must be 3 x 3 [For multiplication rule to be satisfied.] Now we need to fill the Matrix 'C'. So according to our equation. F(n) = a*F(n-1) + b*F(n-2) + c*F(n-3) F(n-1) = F(n-1) F(n-2) = F(n-2) C = [a b c 1 0 0 0 1 0] Now the relation between matrix becomes : [First Matrix] [Second matrix] [Third Matrix] | F(n) | = | a b c | * | F(n-1) | | F(n-1) | | 1 0 0 | | F(n-2) | | F(n-2) | | 0 1 0 | | F(n-3) | Lets assume the initial values for this case :- F(0) = 0 F(1) = 1 F(2) = 1 So, we need to get F(n) in terms of these values. So, for n = 3 Equation (1) changes to | F(3) | = | a b c | * | F(2) | | F(2) | | 1 0 0 | | F(1) | | F(1) | | 0 1 0 | | F(0) | Now similarly for n = 4 | F(4) | = | a b c | * | F(3) | | F(3) | | 1 0 0 | | F(2) | | F(2) | | 0 1 0 | | F(1) | - - - - 2 times - - - | F(4) | = | a b c | * | a b c | * | F(2) | | F(3) | | 1 0 0 | | 1 0 0 | | F(1) | | F(2) | | 0 1 0 | | 0 1 0 | | F(0) | So for n, the Equation (1) changes to - - - - - - - - n -2 times - - - - - | F(n) | = | a b c | * | a b c | * ... * | a b c | * | F(2) | | F(n-1) | | 1 0 0 | | 1 0 0 | | 1 0 0 | | F(1) | | F(n-2) | | 0 1 0 | | 0 1 0 | | 0 1 0 | | F(0) | | F(n) | = [ | a b c | ] ^ (n-2) * | F(2) | | F(n-1) | [ | 1 0 0 | ] | F(1) | | F(n-2) | [ | 0 1 0 | ] | F(0) | So we can simply multiply our Second matrix n-2 times and then multiply it with the third matrix to get the result. Multiplication can be done in (log n) time using Divide and Conquer algorithm for power (See this or this)Let us consider the problem of finding n’th term of a series defined using below recurrence. n'th term, F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3 Base Cases : F(0) = 0, F(1) = 1, F(2) = 1 We can find n’th term using following : Putting a = 1, b = 1 and c = 1 in above formula | F(n) | = [ | 1 1 1 | ] ^ (n-2) * | F(2) | | F(n-1) | [ | 1 0 0 | ] | F(1) | | F(n-2) | [ | 0 1 0 | ] | F(0) | Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find value of f(n) where f(n)// is defined as// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3// Base Cases :// F(0) = 0, F(1) = 1, F(2) = 1#include<bits/stdc++.h>using namespace std; // A utility function to multiply two matrices// a[][] and b[][]. Multiplication result is// stored back in b[][]void multiply(int a[3][3], int b[3][3]){ // Creating an auxiliary matrix to store elements // of the multiplication matrix int mul[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { mul[i][j] = 0; for (int k = 0; k < 3; k++) mul[i][j] += a[i][k]*b[k][j]; } } // storing the multiplication result in a[][] for (int i=0; i<3; i++) for (int j=0; j<3; j++) a[i][j] = mul[i][j]; // Updating our matrix} // Function to compute F raise to power n-2.int power(int F[3][3], int n){ int M[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}}; // Multiply it with initial values i.e with // F(0) = 0, F(1) = 1, F(2) = 1 if (n==1) return F[0][0] + F[0][1]; power(F, n/2); multiply(F, F); if (n%2 != 0) multiply(F, M); // Multiply it with initial values i.e with // F(0) = 0, F(1) = 1, F(2) = 1 return F[0][0] + F[0][1] ;} // Return n'th term of a series defined using below// recurrence relation.// f(n) is defined as// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3// Base Cases :// f(0) = 0, f(1) = 1, f(2) = 1int findNthTerm(int n){ int F[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}} ; //Base cases if(n==0) return 0; if(n==1 || n==2) return 1; return power(F, n-2);} // Driver codeint main(){ int n = 5; cout << "F(5) is " << findNthTerm(n); return 0;} // JAVA program to find value of f(n) where// f(n) is defined as// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3// Base Cases :// F(0) = 0, F(1) = 1, F(2) = 1import java.io.*; class GFG { // A utility function to multiply two // matrices a[][] and b[][]. // Multiplication result is // stored back in b[][] static void multiply(int a[][], int b[][]) { // Creating an auxiliary matrix to // store elements of the // multiplication matrix int mul[][] = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { mul[i][j] = 0; for (int k = 0; k < 3; k++) mul[i][j] += a[i][k] * b[k][j]; } } // storing the multiplication // result in a[][] for (int i=0; i<3; i++) for (int j=0; j<3; j++) // Updating our matrix a[i][j] = mul[i][j]; } // Function to compute F raise to // power n-2. static int power(int F[][], int n) { int M[][] = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}}; // Multiply it with initial values // i.e with F(0) = 0, F(1) = 1, // F(2) = 1 if (n == 1) return F[0][0] + F[0][1]; power(F, n / 2); multiply(F, F); if (n%2 != 0) multiply(F, M); // Multiply it with initial values // i.e with F(0) = 0, F(1) = 1, // F(2) = 1 return F[0][0] + F[0][1] ; } // Return n'th term of a series defined // using below recurrence relation. // f(n) is defined as // f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 // Base Cases : // f(0) = 0, f(1) = 1, f(2) = 1 static int findNthTerm(int n) { int F[][] = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}} ; return power(F, n-2); } // Driver code public static void main (String[] args) { int n = 5; System.out.println("F(5) is " + findNthTerm(n)); }} //This code is contributed by vt_m. # Python3 program to find value of f(n)# where f(n) is defined as# F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3# Base Cases :# F(0) = 0, F(1) = 1, F(2) = 1 # A utility function to multiply two# matrices a[][] and b[][]. Multiplication# result is stored back in b[][]def multiply(a, b): # Creating an auxiliary matrix # to store elements of the # multiplication matrix mul = [[0 for x in range(3)] for y in range(3)]; for i in range(3): for j in range(3): mul[i][j] = 0; for k in range(3): mul[i][j] += a[i][k] * b[k][j]; # storing the multiplication # result in a[][] for i in range(3): for j in range(3): a[i][j] = mul[i][j]; # Updating our matrix return a; # Function to compute F raise# to power n-2.def power(F, n): M = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]; # Multiply it with initial values i.e # with F(0) = 0, F(1) = 1, F(2) = 1 if (n == 1): return F[0][0] + F[0][1]; power(F, int(n / 2)); F = multiply(F, F); if (n % 2 != 0): F = multiply(F, M); # Multiply it with initial values i.e # with F(0) = 0, F(1) = 1, F(2) = 1 return F[0][0] + F[0][1] ; # Return n'th term of a series defined# using below recurrence relation.# f(n) is defined as# f(n) = f(n-1) + f(n-2) + f(n-3), n>=3# Base Cases :# f(0) = 0, f(1) = 1, f(2) = 1def findNthTerm(n): F = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]; return power(F, n - 2); # Driver coden = 5; print("F(5) is", findNthTerm(n)); # This code is contributed by mits // C# program to find value of f(n) where// f(n) is defined as// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3// Base Cases :// F(0) = 0, F(1) = 1, F(2) = 1using System; class GFG { // A utility function to multiply two // matrices a[][] and b[][]. Multiplication // result is stored back in b[][] static void multiply(int[, ] a, int[, ] b) { // Creating an auxiliary matrix to store // elements of the multiplication matrix int[, ] mul = new int[3, 3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { mul[i, j] = 0; for (int k = 0; k < 3; k++) mul[i, j] += a[i, k] * b[k, j]; } } // storing the multiplication result // in a[][] for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) // Updating our matrix a[i, j] = mul[i, j]; } // Function to compute F raise to power n-2. static int power(int[, ] F, int n) { int[, ] M = { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }; // Multiply it with initial values i.e // with F(0) = 0, F(1) = 1, F(2) = 1 if (n == 1) return F[0, 0] + F[0, 1]; power(F, n / 2); multiply(F, F); if (n % 2 != 0) multiply(F, M); // Multiply it with initial values i.e // with F(0) = 0, F(1) = 1, F(2) = 1 return F[0, 0] + F[0, 1]; } // Return n'th term of a series defined // using below recurrence relation. // f(n) is defined as // f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 // Base Cases : // f(0) = 0, f(1) = 1, f(2) = 1 static int findNthTerm(int n) { int[, ] F = { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }; return power(F, n - 2); } // Driver code public static void Main() { int n = 5; Console.WriteLine("F(5) is " + findNthTerm(n)); }} // This code is contributed by vt_m. <?php// PHP program to find value of f(n) where f(n)// is defined as// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3// Base Cases :// F(0) = 0, F(1) = 1, F(2) = 1 // A utility function to multiply two matrices// a[][] and b[][]. Multiplication result is// stored back in b[][]function multiply(&$a, &$b){ // Creating an auxiliary matrix to store // elements of the multiplication matrix $mul = array_fill(0, 3, array_fill(0, 3, 0)); for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) { $mul[$i][$j] = 0; for ($k = 0; $k < 3; $k++) $mul[$i][$j] += $a[$i][$k] * $b[$k][$j]; } } // storing the multiplication result in a[][] for ($i = 0; $i < 3; $i++) for ($j = 0; $j < 3; $j++) $a[$i][$j] = $mul[$i][$j]; // Updating our matrix} // Function to compute F raise to power n-2.function power($F, $n){ $M = array(array(1, 1, 1), array(1, 0, 0), array(0, 1, 0)); // Multiply it with initial values i.e with // F(0) = 0, F(1) = 1, F(2) = 1 if ($n == 1) return $F[0][0] + $F[0][1]; power($F, (int)($n / 2)); multiply($F, $F); if ($n % 2 != 0) multiply($F, $M); // Multiply it with initial values i.e with // F(0) = 0, F(1) = 1, F(2) = 1 return $F[0][0] + $F[0][1] ;} // Return n'th term of a series defined// using below recurrence relation.// f(n) is defined as// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3// Base Cases :// f(0) = 0, f(1) = 1, f(2) = 1function findNthTerm($n){ $F = array(array(1, 1, 1), array(1, 0, 0), array(0, 1, 0)); return power($F, $n - 2);} // Driver code$n = 5; echo "F(5) is " . findNthTerm($n); // This code is contributed by mits?> <script> // javascript program to find value of f(n) where// f(n) is defined as// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3// Base Cases :// F(0) = 0, F(1) = 1, F(2) = 1 // A utility function to multiply two// matrices a and b.// Multiplication result is// stored back in bfunction multiply(a , b){ // Creating an auxiliary matrix to // store elements of the // multiplication matrix var mul = Array(3).fill(0).map(x => Array(3).fill(0)); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { mul[i][j] = 0; for (k = 0; k < 3; k++) mul[i][j] += a[i][k] * b[k][j]; } } // storing the multiplication // result in a for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) // Updating our matrix a[i][j] = mul[i][j];} // Function to compute F raise to// power n-2.function power(F , n){ var M = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]; // Multiply it with initial values // i.e with F(0) = 0, F(1) = 1, // F(2) = 1 if (n == 1) return F[0][0] + F[0][1]; power(F, parseInt(n / 2)); multiply(F, F); if (n % 2 != 0) multiply(F, M); // Multiply it with initial values // i.e with F(0) = 0, F(1) = 1, // F(2) = 1 return F[0][0] + F[0][1] ;} // Return n'th term of a series defined// using below recurrence relation.// f(n) is defined as// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3// Base Cases :// f(0) = 0, f(1) = 1, f(2) = 1function findNthTerm(n){ var F = [[1, 1, 1], [1, 0, 0], [0, 1, 0]] ; return power(F, n-2);} // Driver code var n = 5; document.write("F(5) is " + findNthTerm(n)); // This code is contributed by Princi Singh</script> Output : F(5) is 7 Time Complexity: O(logN)Auxiliary Space: O(logN) This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar nidhi_biet Akanksha_Rai ManasUniyal princi singh pankajsharmagfg Fibonacci matrix-exponentiation Modular Arithmetic series Algorithms Competitive Programming Dynamic Programming Mathematical Matrix Dynamic Programming Mathematical Matrix series Fibonacci Modular Arithmetic Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Algorithms Difference between NP hard and NP complete problem Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 25899, "s": 25871, "text": "\n12 Aug, 2021" }, { "code": null, "e": 26274, "s": 25899, "text": "This is one of the most used techniques in competitive programming. Let us first consider below simple question.What is the minimum time complexity to find n’th Fi...
Find a permutation of 1 to N, such that A is minimum in left half and B is maximum in right half - GeeksforGeeks
28 Jan, 2022 Given three integers N, A, and B, the task is to find a permutation of pairwise distinct numbers from 1 to N such that A is the minimum element of the left half and B is the maximum element of the right half. It is also given that N is even. If no such permutations exist print -1. Examples: Input: N = 6, A = 2, B = 5Output: 6, 2, 4, 3, 5, 1Explanation: A = 2 is the minima of the left half.B = 5 is the maxima of the right half. Input: N = 6, A = 1, B = 3Output: -1Explanation: No such permutation exists. Naive Approach (Brute Force): In this approach, generate all permutations of 1 to N numbers and check each one individually. Follow the below steps, to solve this problem: Generate all the permutations of numbers from 1 to N and store them in an array. Traverse through each permutation, if in the following permutation A is the minima of the left half and B is the maxima of the right half then print the permutation. If no such permutation exists, then print -1. Below is the implementation of the above approach: C++ Python3 // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate next permutationvoid nextPermutation(vector<int>& nums){ int n = nums.size(), k, l; for (k = n - 2; k >= 0; k--) { if (nums[k] < nums[k + 1]) { break; } } if (k < 0) { reverse(nums.begin(), nums.end()); } else { for (l = n - 1; l > k; l--) { if (nums[l] > nums[k]) { break; } } swap(nums[k], nums[l]); reverse(nums.begin() + k + 1, nums.end()); }} // Factorial functionint factorial(int n){ return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;} // Function to returns all the permutations// of a given array or vectorvector<vector<int> > permute(vector<int>& nums){ vector<vector<int> > permuted; int n = nums.size(); int factn = factorial(n); for (int i = 0; i < factn; i++) { permuted.push_back(nums); nextPermutation(nums); } return permuted;} // Function to find the permutation// of 1 to N numbers// having A minimas and B maximasvoid findPermutation(int n, int a, int b){ // Generate the array // containing one permutation vector<int> nums(n); for (int i = 0; i < n; i++) { nums[i] = i + 1; } // Generate all the permutations vector<vector<int> > allpermutations = permute(nums); int total = allpermutations.size(); int ansindex = -1; for (int i = 0; i < total; i++) { // Find the minima of the left half // maxima of the right half int leftmin = allpermutations[i][0]; int rightmax = allpermutations[i][n - 1]; for (int j = 0; j < n / 2; j++) { if (allpermutations[i][j] < leftmin) { leftmin = allpermutations[i][j]; } } for (int j = n / 2; j < n; j++) { if (allpermutations[i][j] > rightmax) { rightmax = allpermutations[i][j]; } } if (leftmin == a && rightmax == b) { // Store the index // of a perfect permutation ansindex = i; break; } } // Print -1 if no such permutation exists if (ansindex == -1) { cout << -1; } else { // Print the perfect permutation if exists for (int i = 0; i < n; i++) { cout << allpermutations[ansindex][i] << " "; } }} // Driver Codeint main(){ int N = 6, A = 2, B = 5; findPermutation(N, A, B); return 0;} # Python code to implement the above approach num =[]# Function to generate next permutationdef nextPermutation(nums): global num n = len(nums) for k in range(n - 2, -1,-1): if (nums[k] < nums[k + 1]): break if (k < 0): nums.reverse() else: for l in range(n - 1, k, -1): if (nums[l] > nums[k]): break nums[k], nums[l] = nums[l], nums[k] temp = nums[k+1:] temp.reverse() nums = nums[:k+1] +temp return nums # Factorial functiondef factorial(n): return 1 if(n == 1 or n == 0) else factorial(n - 1) * n # Function to returns all the permutations# of a given array or vectordef permute(nums): global num permuted =[] n = len(nums) factn = factorial(n) for i in range(factn): permuted.append(nums) nums = nextPermutation(nums) permuted.append(nums) return permuted # Function to find the permutation# of 1 to N numbers# having A minimas and B maximasdef findPermutation(n, a, b): # Generate the array # containing one permutation nums = [0]*n for i in range(n): nums[i] = i + 1 # Generate all the permutations allpermutations = permute(nums) total = len(allpermutations) ansindex = -1 for i in range(total): # Find the minima of the left half # maxima of the right half leftmin = allpermutations[i][0] rightmax = allpermutations[i][n - 1] for j in range(n // 2): if (allpermutations[i][j] < leftmin): leftmin = allpermutations[i][j] for j in range(n // 2,n): if (allpermutations[i][j] > rightmax): rightmax = allpermutations[i][j] if (leftmin == a and rightmax == b): # Store the index # of a perfect permutation ansindex = i break # Pr-1 if no such permutation exists if (ansindex == -1): print(-1) else: # Print the perfect permutation if exists for i in range(n): print(allpermutations[ansindex][i], end =" ") # Driver CodeN = 6A = 2B = 5findPermutation(N, A, B) # This code is contributed by Shubham Singh 2 3 6 1 4 5 Time Complexity: O(N!)Auxiliary Space: O(N!) Efficient Approach (Greedy Method): The above brute force method can be optimized using the Greedy Algorithm. Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So, break the problem into different usable pieces according to the values of N, A, B. Follow the below steps to solve this problem: Initialize the variables left as n-b and right as a-1. If left or right is greater than n/2 then print -1 Else if a and b are less than equal to n/2 then print -1. Else if a and b are greater than n/2 then print -1. Else if a equals n/2+1 and b equals n/2 then print n to 1 as the answer. Else, iterate over the range [0, n) using the variable i and perform the following tasks:If n-i equals a or b then print a or b else print n-i. If n-i equals a or b then print a or b else print n-i. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get the desired permutationvoid getpermutation(int n, int a, int b){ int left = n - b, right = a - 1; // When b < n/2 or a > n/2 if (left > n / 2 || right > n / 2) { cout << -1; } // When a and b both are // in the same half else if (a <= n / 2 && b <= n / 2) { cout << -1; } else if (a > n / 2 && b > n / 2) { cout << -1; } // The corner case else if (a == n / 2 + 1 && b == n / 2) { for (int i = 0; i < n; i++) { cout << n - i << " "; } } // Rest other combinations else { for (int i = 0; i < n; i++) { if (n - i == b) { cout << a << " "; } else if (n - i == a) { cout << b << " "; } else { cout << n - i << " "; } } } cout << endl;} // Driver Codeint main(){ int N = 6, A = 2, B = 5; getpermutation(N, A, B); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to get the desired permutationstatic void getpermutation(int n, int a, int b){ int left = n - b, right = a - 1; // When b < n/2 or a > n/2 if (left > n / 2 || right > n / 2) { System.out.print(-1); } // When a and b both are // in the same half else if (a <= n / 2 && b <= n / 2) { System.out.print(-1); } else if (a > n / 2 && b > n / 2) { System.out.print(-1); } // The corner case else if (a == n / 2 + 1 && b == n / 2) { for(int i = 0; i < n; i++) { System.out.print(n - i + " "); } } // Rest other combinations else { for(int i = 0; i < n; i++) { if (n - i == b) { System.out.print(a + " "); } else if (n - i == a) { System.out.print(b + " "); } else { System.out.print(n - i + " "); } } } System.out.println();} // Driver Codepublic static void main(String args[]){ int N = 6, A = 2, B = 5; getpermutation(N, A, B);}} // This code is contributed by Samim Hossain Mondal. # python program for the above approach # Function to get the desired permutationdef getpermutation(n, a, b): left = n - b right = a - 1 # When b < n/2 or a > n/2 if (left > n / 2 or right > n / 2): print(-1) # When a and b both are # in the same half elif (a <= n / 2 and b <= n / 2): print(-1) elif (a > n / 2 and b > n / 2): print(-1) # The corner case elif (a == n / 2 + 1 and b == n / 2): for i in range(0, n): print(n - i, end=" ") # Rest other combinations else: for i in range(0, n): if (n - i == b): print(a, end=" ") elif (n - i == a): print(b, end=" ") else: print(n - i, end=" ") print() # Driver Codeif __name__ == "__main__": N = 6 A = 2 B = 5 getpermutation(N, A, B) # This code is contributed by rakeshsahni // C# program for the above approachusing System;class GFG { // Function to get the desired permutation static void getpermutation(int n, int a, int b) { int left = n - b, right = a - 1; // When b < n/2 or a > n/2 if (left > n / 2 || right > n / 2) { Console.Write(-1); } // When a and b both are // in the same half else if (a <= n / 2 && b <= n / 2) { Console.Write(-1); } else if (a > n / 2 && b > n / 2) { Console.Write(-1); } // The corner case else if (a == n / 2 + 1 && b == n / 2) { for (int i = 0; i < n; i++) { Console.Write(n - i + " "); } } // Rest other combinations else { for (int i = 0; i < n; i++) { if (n - i == b) { Console.Write(a + " "); } else if (n - i == a) { Console.Write(b + " "); } else { Console.Write(n - i + " "); } } } Console.WriteLine(); } // Driver Code public static void Main() { int N = 6, A = 2, B = 5; getpermutation(N, A, B); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to get the desired permutation function getpermutation(n, a, b) { let left = n - b, right = a - 1; // When b < n/2 or a > n/2 if (left > Math.floor(n / 2) || right > Math.floor(n / 2)) { document.write(-1 + " "); } // When a and b both are // in the same half else if (a <= Math.floor(n / 2) && b <= Math.floor(n / 2)) { document.write(-1 + " "); } else if (a > Math.floor(n / 2) && b > Math.floor(n / 2)) { document.write(-1 + " "); } // The corner case else if (a == Math.floor(n / 2) + 1 && b == Math.floor(n / 2)) { for (let i = 0; i < n; i++) { document.write(n - i + " "); } } // Rest other combinations else { for (let i = 0; i < n; i++) { if (n - i == b) { document.write(a + " ") } else if (n - i == a) { document.write(b + " ") } else { document.write(n - i + " ") } } } cout << endl; } // Driver Code let N = 6, A = 2, B = 5; getpermutation(N, A, B); // This code is contributed by Potta Lokesh </script> 6 2 4 3 5 1 Time Complexity: O(N)Auxiliary Space: O(N) lokeshpotta20 rakeshsahni ukasp samim2000 shubhamsingh84100 adnanirshad158 Algo-Geek 2021 permutation Algo Geek Arrays Combinatorial Greedy Arrays Greedy permutation Combinatorial 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 Smallest set of vertices to visit all nodes of the given Graph 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": 27533, "s": 27505, "text": "\n28 Jan, 2022" }, { "code": null, "e": 27815, "s": 27533, "text": "Given three integers N, A, and B, the task is to find a permutation of pairwise distinct numbers from 1 to N such that A is the minimum element of the left half an...
Mongoose | deleteMany() Function - GeeksforGeeks
20 May, 2020 The deleteMany() function is used to delete all of the documents that match conditions from the collection. This function behaves like the remove() function but it deletes all documents that match conditions regardless of the single option. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for, example index.js. To run this file you need to run the following command.node index.js You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file for, example index.js. To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function call// Deleting all users whose age >= 15User.deleteMany({ age: { $gte: 15 } }).then(function(){ console.log("Data deleted"); // Success}).catch(function(error){ console.log(error); // Failure}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the deleteMany() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter running above command, your can see the data is deleted from the database. The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the deleteMany() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After running above command, your can see the data is deleted from the database. So this is how you can use mongoose deleteMany() function to delete multiple documents from the collection in MongoDB and Node.js. Mongoose JavaScript MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Upload and Retrieve Image on MongoDB using Mongoose Spring Boot JpaRepository with Example Login form using Node.js and MongoDB Aggregation in MongoDB Mongoose Populate() Method
[ { "code": null, "e": 26023, "s": 25995, "text": "\n20 May, 2020" }, { "code": null, "e": 26264, "s": 26023, "text": "The deleteMany() function is used to delete all of the documents that match conditions from the collection. This function behaves like the remove() function but it...
Scheduling priority tasks in limited time and minimizing loss - GeeksforGeeks
26 Nov, 2018 Given n tasks with arrival time, priority and number of time units they need. We need to schedule these tasks on a single resource. The objective is to arrange tasks such that maximum priority tasks are taken. Objective is to minimize sum of product of priority and left time of tasks that are not scheduled due to limited time. This criteria simply means that the scheduling should cause minimum possible loss. Examples: Input : Total time = 3 Task1: arrival = 1, units = 2, priority = 300 Task2: arrival = 2, units = 2, priority = 100 Output : 100 Explanation : Two tasks are given and time to finish them is 3 units. First task arrives at time 1 and it needs 2 units. Since no other task is running at that time, we take it. 1 unit of task 1 is over. Now task 2 arrives. The priority of task 1 is more than task 2 (300 > 100) thus 1 more unit of task 1 is employed. Now 1 unit of time is left and we have 2 units of task 2 to be done. So simply 1 unit of task 2 is done and the answer is ( units of task 2 left X priority of task 2 ) = 1 X 100 = 100 Input : Total Time = 3 Task1: arrival = 1, units = 1, priority = 100 Task2: arrival = 2, units = 2, priority = 300 Output : 0 We use a priority queue and schedule one unit of task at a time. Initialize total loss as sum of each priority and units. The idea is to initialize result as maximum, then one by one subtract priorities of tasks that are scheduled.Sort all tasks according to arrival time.Process through each unit of time from 1 to total time. For current time, pick the highest priority task that is available. Schedule 1 unit of this task and subtract its priority from total loss. Initialize total loss as sum of each priority and units. The idea is to initialize result as maximum, then one by one subtract priorities of tasks that are scheduled. Sort all tasks according to arrival time. Process through each unit of time from 1 to total time. For current time, pick the highest priority task that is available. Schedule 1 unit of this task and subtract its priority from total loss. Below is C++ implementation of above steps. // C++ code for task scheduling on basis// of priority and arrival time#include "bits/stdc++.h"using namespace std; // t is total time. n is number of tasks.// arriv[] stores arrival times. units[]// stores units of time required. prior[]// stores priorities.int minLoss(int n, int t, int arriv[], int units[], int prior[]){ // Calculating maximum possible answer // that could be calculated. Later we // will subtract the tasks from it // accordingly. int ans = 0; for (int i = 0; i < n; i++) ans += prior[i] * units[i]; // Pushing tasks in a vector so that they // could be sorted according with their // arrival time vector<pair<int, int> > v; for (int i = 0; i < n; i++) v.push_back({ arriv[i], i }); // Sorting tasks in vector identified by // index and arrival time with respect // to their arrival time sort(v.begin(), v.end()); // Priority queue to hold tasks to be // scheduled. priority_queue<pair<int, int> > pq; // Consider one unit of time at a time. int ptr = 0; // index in sorted vector for (int i = 1; i <= t; i++) { // Push all tasks that have arrived at // this time. Note that the tasks that // arrived earlier and could not be scheduled // are already in pq. while (ptr < n and v[ptr].x == i) { pq.push({ prior[v[ptr].y], units[v[ptr].y] }); ptr++; } // Remove top priority task to be scheduled // at time i. if (!pq.empty()) { auto tmp = pq.top(); pq.pop(); // Removing 1 unit of task // from answer as we could // schedule it. ans -= tmp.x; tmp.y--; if (tmp.y) pq.push(tmp); } } return ans;} // driver codeint main(){ int n = 2, t = 3; int arriv[] = { 1, 2 }; int units[] = { 2, 2 }; int prior[] = { 100, 300 }; printf("%d\n", minLoss(n, t, arriv, units, prior)); return 0;} Output: 100 This article is contributed by Parth Trehan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. featured Greedy Heap Greedy Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem Difference between Prim's and Kruskal's algorithm for MST Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm HeapSort Binary Heap K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array Building Heap from Array
[ { "code": null, "e": 25667, "s": 25639, "text": "\n26 Nov, 2018" }, { "code": null, "e": 26079, "s": 25667, "text": "Given n tasks with arrival time, priority and number of time units they need. We need to schedule these tasks on a single resource. The objective is to arrange tas...
PyQt5 - nextCheckState() method for Check Box - GeeksforGeeks
22 Apr, 2020 We can set the state of the check box using setChecked or for tristate check box we can set its states using setCheckState method. nextCheckState sets the next state of the check box i.e for default check box if initial check state is checked, it will set it to un-checed and vice versa. For tri-state check box if check state if un-checked it will set it to intermediate state and if initial state is intermediate, it will set it to checked and if it is checked it will set it to un-checked. Syntax : checkbox.nextCheckState() Argument : It takes no argument. Action performed : It will change the state of check box according to the previous state. Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 40) # making it tristate check box checkbox.setTristate(True) # setting check box to its next state checkbox.nextCheckState() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25668, "s": 25537, "text": "We can set the state of the check box using setChecked or for tristate check box we can set its states using setCheckState method." }, { "code": null, ...
Project Idea | Animal Welfare and Wellness Web Application - GeeksforGeeks
27 Jul, 2021 Abstract — Drawing the idea from the influence of social networking sites on our day-to-day life and Web Application for the betterment of pets that will be developed by using the concept of native Web Application development. The currently working module can be seen on URL — loyalfriend.biz The “LoyalFriend is a web-based application wherein the welfare of pet animals is taken care of. It is a place where stray, lost, abandoned, or surrendered pets are brought and severed. Each pet requires special care and attention which is fulfilled in the organization. The application allows the user to adopt a pet, volunteer towards the pet, purchase the products that are related to pets and donate the desired amount to the organization. Since this application is developed for a non-profitable organization, the amount donated will be utilized for the welfare of the pets. The user of the application can work towards a pet as a volunteer and also he/she can adopt the pet from the application. The application contains pets’ related products such as food, grooming products, etc. for purchase. The purchase of products is done using a credit card, debit card, or cash on delivery. The application also provides guidelines to the user regarding the health care of pets, how the pets need to be nurtured, how they have to be taken care of after being adopted. HTML 5, CSS3, and JavaScript are used to develop the application. The back end of the application uses NodeJS package managers like npm and yarn, also NodeJS provides functionalities to create easy-to-deploy development servers that are relatively easy to debug. Purpose — The main purpose of this project is to automate the process of serving towards the welfare of the pets by giving the abandoned pets a place of shelter to live in, care for them with affection. The scope of the project is limited to the intranet for time being it is not deployable on any handheld devices. To provide ease of working towards the welfare of abandoned, stray, lost, or surrendered pets. It saves time, paperwork is less, and easy retrieval of records, automating the system reduces the process of middle man who takes a commission. Introduction — The current system of grooming the pets is done manually which is time-consuming. Maintaining records is difficult and maybe misplaced which leads to a lot of confusion or a great fuss. The main idea of this project is to provide a user-friendly interface to automate the process of serving towards the welfare of the pets by giving the abandoned pets a place of shelter and care them with affection. The application also gives guidelines for caring for the pets, the adoption procedure of a pet, and volunteering towards the pets. The user can do the adoption process through the application as this process is time-consuming if done manually. The application provides the user an option of donating any amount to the organization. The donation can be done using cash, cards. The user can register them to the organization through the application and choose their area of interest as to work as a volunteer, adopting a pet, or purchasing the products related to pets. For adoption as well as volunteering, the user can choose the pets that are in the organization view their details, and if they wish they can continue with the process of adoption or volunteer. Objective and Scope — The main objective of this project is to automate the process of serving towards the welfare of the pets by giving the abandoned pets a place of shelter, care for them with affection. The scope of the project is limited to the intranet for time being it is not deployable on any handheld devices. To provide ease of working towards the welfare of abandoned, stray, lost, or surrendered pets. It saves time, paperwork is less, and easy retrieval of records, automating the system reduces the process of middle man who takes a commission. Requirements – 1. Hardware Requirements Processor: Intel(R) Pentium(R) or above CPU Hard disk: 500GB HDD RAM: 4GB RAM 2. Software Requirements Operating System: Windows 7 and above Front End: HTML 5, CSS 3, JavaScript Back End: JavaScript, Node.js, MongoDB, Pug, Mongoose Module Description — The project is divided into different modules: Login Page/Sign Up — On this page, the user can create a new profile or log in to their profiles using their username and password. On the profile page, the user can view their profiles, what they have posted or shared. Image feed — This will be the news feed page, where user can see posts shared by the Organizations and the recommended pages which contains all the necessary details about the adoption centers and the pets available to adopt. Project SOS — On this page, people can post about abandoned animals and help them find a home/shelter. About us — This page will show the details about the developer’s team. Access to help box-Authentic users will get access to chat with the adoption center directly on the webpage with a feature of Help Box if a user is not willing to share the contact number. Features– Login/Signup modules Live previews Full-screen mode Cross-platform Password Hashing Interactive UI Run Locally – Clone the project git clone https://github.com/anshulhub/LoyalFriend.git Go to the project directory cd LoyalFriend Install dependencies npm install Start the server npm run start Data-Flow Diagrams – Level 0 – Level 1 – Flow Chart- Future Scope — The project aims to build a pet-friendly Web Application where the users can get connected, share their pet’s pictures, and also share the picture of some abandoned animals they come across, through which a shelter can be searched for the poor animal. The project also displays items that can be bought by users for their pets’ nourishment and care. The future implementation of this project is that later GPS location will be added to the site through which location of the abandoned animals and shelter for them can be reached easily. Other features like creative dog emoji and changes in the CSS of the page will be implemented. As the project is a pet-friendly site, more pet-friendly products will be added to the purchasing frame of the site. Conclusion — The proposed system is designed in HTML and developed using JavaScript. The back end of the project is developed using NodeJS to work with yarn and npm packages. The project is a web application that has similar functionality to either a desktop software application or a mobile application. The project aims to introduce a pet-friendly Web Application where shelters are found for an abandoned animal whose information is uploaded on the site by the users connected here, that in result raises awareness among people about the plight of strays and how each one of us can ensure a better and safer environment for these animals. ProGeek 2021 ProGeek Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Handwritten Digit Recognition using Neural Network AI Driven Snake Game using Deep Q Learning Rock, Paper, Scissor game - Python Project Twitter Sentiment Analysis WebApp Using Flask How to Build a Cryptocurrency Tracker Android App? 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26355, "s": 26327, "text": "\n27 Jul, 2021" }, { "code": null, "e": 26584, "s": 26355, "text": "Abstract — Drawing the idea from the influence of social networking sites on our day-to-day life and Web Application for the betterment of pets that will be develo...
Types of Program Control Instructions
16 Aug, 2021 Program Control Instructions are the machine code that are used by machine or in assembly language by user to command the processor act accordingly. These instructions are of various types. These are used in assembly language by user also. But in level language, user code is translated into machine code and thus instructions are passed to instruct the processor do the task. Types of Program Control Instructions: There are different types of Program Control Instructions: 1. Compare Instruction: Compare instruction is specifically provided, which is similar to a subtract instruction except the result is not stored anywhere, but flags are set according to the result. Example: CMP R1, R2 ; 2. Unconditional Branch Instruction: It causes an unconditional change of execution sequence to a new location. Example: JUMP L2 Mov R3, R1 goto L2 3. Conditional Branch Instruction: A conditional branch instruction is used to examine the values stored in the condition code register to determine whether the specific condition exists and to branch if it does. Example: Assembly Code : BE R1, R2, L1 Compiler allocates R1 for x and R2 for y High Level Code: if (x==y) goto L1; 4. Subroutines: A subroutine is a program fragment that lives in user space, performs a well-defined task. It is invoked by another user program and returns control to the calling program when finished. Example: CALL and RET 5. Halting Instructions: NOP Instruction – NOP is no operation. It cause no change in the processor state other than an advancement of the program counter. It can be used to synchronize timing. HALT – It brings the processor to an orderly halt, remaining in an idle state until restarted by interrupt, trace, reset or external action. 6. Interrupt Instructions: Interrupt is a mechanism by which an I/O or an instruction can suspend the normal execution of processor and get itself serviced. RESET – It reset the processor. This may include any or all setting registers to an initial value or setting program counter to standard starting location. TRAP – It is non-maskable edge and level triggered interrupt. TRAP has the highest priority and vectored interrupt. INTR – It is level triggered and maskable interrupt. It has the lowest priority. It can be disabled by resetting the processor. tornadomess18 microprocessor Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Aug, 2021" }, { "code": null, "e": 430, "s": 52, "text": "Program Control Instructions are the machine code that are used by machine or in assembly language by user to command the processor act accordingly. These instructions are of...
How to create index for MongoDB Collection using Python?
04 Jul, 2022 Prerequisites: MongoDB Python Basics This article focus on the create_index() method of PyMongo library. Indexes makes it efficient to perform query requests as it stores the data in a way that makes it quick & easy to traverse. Let’s begin with the create_index() method: Importing PyMongo Module: Import the PyMongo module using the command: Importing PyMongo Module: Import the PyMongo module using the command: from pymongo import MongoClient If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number). If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number). client = MongoClient(‘localhost’, 27017) Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database. Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database. mydatabase = client.name_of_the_database Accessing the Collection: We now select the collection from the database using the following syntax: Accessing the Collection: We now select the collection from the database using the following syntax: collection_name = mydatabase.name_of_collection Creating an index: Now we will create the index using create_index() function. Creating an index: Now we will create the index using create_index() function. Syntax: create_index(keys, session=None, **kwargs) keys: Takes either a single key or a list of (key, direction) pairs. session (optional): a ClientSession. arguments **kwargs (optional): any additional index creation option Example: Sample Database: Python3 # Python program to demonstrate# create_index() method # Importing Libraryfrom pymongo import MongoClient, ASCENDING # Connecting to MongoDB server# client = MongoClient('host_name', 'port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student mycollection.create_index('Roll No', unique = True) # Inserting into Databasemycollection.insert_one({'_id':8 , 'name': 'Deepanshu', 'Roll No': '1008', 'Branch': 'IT'}) # Inserting with the same Roll no again.# As the Roll no field is the index and# is set to unique it will through the error.mycollection.insert_one({'_id':9 , 'name': 'Hitesh', 'Roll No': '1008', 'Branch': 'CSE'}) Output: DuplicateKeyError Traceback (most recent call last) in 36 ‘name’: ‘Hitesh’, 37 ‘Roll No’: ‘1008’, —> 38 ‘Branch’: ‘CSE’}) DuplicateKeyError: E11000 duplicate key error collection: GFG.Student index: Roll No_1 dup key: { : “1008” } MongoDB Shell: It raises the DuplicateKeyError as there is already a document that exists with the Roll No 1008 and we are trying to insert another document with the same Roll No. This error occurs because we created an index on the field Roll No and marked it as unique. khushb99 Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 301, "s": 28, "text": "Prerequisites: MongoDB Python Basics This article focus on the create_index() method of PyMongo library. Indexes makes it efficient to perform query requests as it stores the ...
Mixtures and Alligation - GeeksforGeeks
30 Nov, 2021 Let the amount taken from S1 be 7x And amount taken from S2 be 13y (2x + 6y)/(5x + 7y) = 5/8 16x + 48y = 25x + 35y 9x = 13y x/y = 13/9 Actual ratios of amounts = 7x/13y = (7/13) * (13/9) = 7/9 Concentration of orange pulp in 1st vessel Concentration of orange pulp in 2nd vessel 40% 19% 26% 40-26=14 CP of 1 kg rice of 1st kind CP of 1 kg rice of 2nd kind Rs. 9 Rs.8.4 8.4 - 7 = 1.4 9 - 8.4 = 0.6 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29577, "s": 29549, "text": "\n30 Nov, 2021" }, { "code": null, "e": 29819, "s": 29577, "text": "Let the amount taken from S1 be 7x\nAnd amount taken from S2 be 13y\n\n(2x + 6y)/(5x + 7y) = 5/8\n16x + 48y = 25x + 35y\n9x = 13y\nx/y = 13/9\n\nActual ratios of a...
Rebuilding or Repairing MySQL Tables or Indexes
Changes to tables and indexes refers to how MySQL handles data types and character sets. The necessary table repairs or upgrades are reported by CHECK TABLE, mysqlcheck, or mysql_upgrade. There are many methods to rebuild a table. Some of them have been listed below − Dump and Reload Method Dump and Reload Method ALTER TABLE Method ALTER TABLE Method REPAIR TABLE Method REPAIR TABLE Method Let us understand each of them in brief − If the tables are being rebuilt due to the fact that different versions of MySQL version can’t handle the tables after a binary (in-place) upgrade or download, then this dump and reload method needs to be used. A table can be rebuilt by dumping and reloading it. This can be done by using the ‘mysqldump’ and creating a dump file and allowing mysql to reload the file. This can be done using the below commands − mysqldump db_name t1 > dump.sql mysql db_name < dump.sql If all the tables have to be rebuilt in a single database, the name of the database can be specified without using any table name. It can be done using the below command − mysqldump db_name > dump.sql mysql db_name < dump.sql If all the tables in all the databases have to be rebuilt, then the ‘− − all databases’ option has to be used. It can be done using the below command − mysqldump --all-databases > dump.sql mysql < dump.sql If a table needs to be rebuilt using the ALTER TABLE method, then a “null” alteration can be used. An ALTER TABLE statement can be used which changes the table so that it can use the storage engine. Let us take an example: Suppose TblName is an InnoDB table, the below statement can be used to rebuild the table − ALTER TABLE TblName ENGINE = InnoDB; The REPAIR TABLE method is only applicable to MyISAM, ARCHIVE, and CSV tables. The statement REPAIR TABLE can be used if the table checking operation suggests that the file has been corrupted or an upgrade is required. Let us take an example: In order to repair a MyISAM table, the below statement can be executed − REPAIR TABLE TblName; mysqlcheck −−repair provides command−line access to the REPAIR TABLE statement. This can be a more convenient means of repairing tables because you can use the −−databases to repair a specific table in a database or −−all−databases option to repair all tables in all databases. It can be done using the below commands − mysqlcheck −−repair −−databases db_name ... mysqlcheck −−repair −−all−databases
[ { "code": null, "e": 1250, "s": 1062, "text": "Changes to tables and indexes refers to how MySQL handles data types and character sets. The necessary table repairs or upgrades are reported by CHECK TABLE, mysqlcheck, or mysql_upgrade." }, { "code": null, "e": 1331, "s": 1250, "te...
jQuery Effects - Fading
With jQuery you can fade elements in and out of visibility. Click to fade in/out panel Because time is valuable, we deliver quick and easy learning. At W3Schools, you can study everything you need to learn, in an accessible and handy format. jQuery fadeIn() Demonstrates the jQuery fadeIn() method. jQuery fadeOut() Demonstrates the jQuery fadeOut() method. jQuery fadeToggle() Demonstrates the jQuery fadeToggle() method. jQuery fadeTo() Demonstrates the jQuery fadeTo() method. With jQuery you can fade an element in and out of visibility. jQuery has the following fade methods: fadeIn() fadeOut() fadeToggle() fadeTo() The jQuery fadeIn() method is used to fade in a hidden element. Syntax: The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeIn() method with different parameters: The jQuery fadeOut() method is used to fade out a visible element. Syntax: The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeOut() method with different parameters: The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods. If the elements are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them out. Syntax: The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeToggle() method with different parameters: The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1). Syntax: The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds. The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1). The optional callback parameter is a function to be executed after the function completes. The following example demonstrates the fadeTo() method with different parameters: Use a jQuery method to fade out a <div> element. $("div").(); Start the Exercise For a complete overview of all jQuery effects, please go to our jQuery Effect Reference. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 60, "s": 0, "text": "With jQuery you can fade elements in and out of visibility." }, { "code": null, "e": 87, "s": 60, "text": "Click to fade in/out panel" }, { "code": null, "e": 149, "s": 87, "text": "Because time is valuable, we deliver...
Compute value of Log Normal Quantile Function in R Programming - qlnorm() Function - GeeksforGeeks
25 Jun, 2020 qlnorm() function in R Language is used to compute the value of log normal quantile function. It also creates a plot of the quantile function of log normal distribution. Syntax: qlnorm(vec) Parameters:vec: x-values for normal density Example 1: # R program to compute value of# log normal quantile function # Creating x-values for densityx <- seq(0, 1, by = 0.2) # Calling qlnorm() functiony <- qlnorm(x)y Output: [1] 0.0000000 0.4310112 0.7761984 1.2883304 2.3201254 Inf Example 2: # R program to compute value of# log normal quantile function # Creating x-values for densityx <- seq(0, 1, by = 0.02) # Calling qlnorm() functiony <- qlnorm(x) # Plot a graphplot(y) Output: R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25021, "s": 24851, "text": "qlnorm() function in R Language is used to compute the value of log normal quantile function. It also creates a plot of the quantile function of log normal distrib...
Google Charts - Quick Guide
Google Charts is a pure JavaScript based charting library meant to enhance web applications by adding interactive charting capability. It supports a wide range of charts. Charts are drawn using SVG in standard browsers like Chrome, Firefox, Safari, Internet Explorer(IE). In legacy IE 6, VML is used to draw the graphics. Following are the salient features of Google Charts library. Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS. Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS. Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets. Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets. Free to Use − Open source and is free to use for non-commercial purpose. Free to Use − Open source and is free to use for non-commercial purpose. Lightweight − loader.js core library, is extremely lightweight library. Lightweight − loader.js core library, is extremely lightweight library. Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use. Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use. Dynamic − Allows to modify chart even after chart generation. Dynamic − Allows to modify chart even after chart generation. Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts. Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts. Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically. Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically. DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories. DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories. Print − Print chart using web page. Print − Print chart using web page. External data − Supports loading data dynamically from server. Provides control over data using callback functions. External data − Supports loading data dynamically from server. Provides control over data using callback functions. Text Rotation − Supports rotation of labels in any direction. Text Rotation − Supports rotation of labels in any direction. Google Charts library provides following types of charts − Line Charts Used to draw line/spline based charts. Area Charts Used to draw area wise charts. Pie Charts Used to draw pie charts. Sankey Charts, Scatter Charts, Stepped area charts, Table, Timelines, TreeMap, Trendlines Used to draw scattered charts. Bubble Charts Used to draw bubble based charts. Dynamic Charts Used to draw dynamic charts where user can modify charts. Combinations Used to draw combinations of variety of charts. 3D Charts Used to draw 3D charts. Angular Gauges Used to draw speedometer type charts. Heat Maps Used to draw heat maps. Tree Maps Used to draw tree maps. In next chapters, we're going to discuss each type of above mentioned charts in details with examples. Google Charts is open source and is free to use. Follow the link: Terms of Service. In this chapter we will discuss about how to set up Google Charts library to be used in web application development. There are two ways to use Google Charts. Download − Download it locally from https://developers.google.com/chart and use it. Download − Download it locally from https://developers.google.com/chart and use it. CDN access − You also have access to a CDN. The CDN will give you access around the world to regional data centers that in this case, Google Chart host https://www.gstatic.com/charts. CDN access − You also have access to a CDN. The CDN will give you access around the world to regional data centers that in this case, Google Chart host https://www.gstatic.com/charts. Include the googlecharts JavaScript file in the HTML page using following script − <head> <script src = "/googlecharts/loader.js"></script> </head> Include the Google Chart JavaScript file in the HTML page using following script − <head> <script src = "https://www.gstatic.com/charts/loader.js"></script> </head> In this chapter we'll showcase the configuration required to draw a chart using Google Chart API. Create an HTML page with the Google Chart libraries. googlecharts_configuration.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> </body> </html> Here container div is used to contain the chart drawn using Google Chart library. Here we are loading the latest version of corecharts API using google.charts.load method. Google Chart library uses very simple configurations using json syntax. // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('container')); chart.draw(data, options); Here data represents the json data and options represents the configuration which Google Chart library uses to draw a chart withing container div using draw() method. Now we'll configure the various parameter to create the required json string. Configure the options of the chart. // Set chart options var options = {'title':'Browser market shares at a specific website, 2014', 'width':550, 'height':400}; Configure the data to be displayed on the chart. DataTable is a special table structured collection which contains the data of the chart. Columns of data table represents the legends and rows represents the corresponding data. addColumn() method is used to add a column where first parameter represents the data type and second parameter represents the legend. addRows() method is used to add rows accordingly. // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Browser'); data.addColumn('number', 'Percentage'); data.addRows([ ['Firefox', 45.0], ['IE', 26.8], ['Chrome', 12.8], ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ]); // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('container')); chart.draw(data, options); Following is the complete example − googlecharts_configuration.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Browser'); data.addColumn('number', 'Percentage'); data.addRows([ ['Firefox', 45.0], ['IE', 26.8], ['Chrome', 12.8], ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ]); // Set chart options var options = {'title':'Browser market shares at a specific website, 2014', 'width':550, 'height':400}; // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById ('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Following code call drawChart function to draws chart when Google Chart library get loaded completely. google.charts.setOnLoadCallback(drawChart); Verify the result. Area charts are used to draw area based charts. In this section we're going to discuss following types of area based charts. Basic area chart Area chart having negative values. Chart having areas stacked over one another. Chart with data in percentage terms. Chart with missing points in the data. Area using inverted axes. Bar charts are used to draw bar based charts. In this section we're going to discuss following types of bar based charts. Basic bar chart Grouped Bar chart. Bar chart having bar stacked over one another. Bar chart with negative stack. Bar Chart with data in percentage terms. A Material Design inspired bar chart. Bar chart with data labels. Bubble charts are used to draw bubble based charts. In this section we're going to discuss following types of bubble based charts. Basic bubble chart. Bubble chart with data labels. Calendar charts are used to draw activities over the course of long span of time like months or years. In this section we're going to discuss following types of calendar based charts. Basic Calendar chart. Customized Calendar Chart. Candlestick charts are used to show opening and closing value over a value variance and are normally used to represent stocks. In this section we're going to discuss following types of candlestick based charts. Basic Candlestick chart. Customized Candlestick Chart. Column charts are used to draw column based charts. In this section we're going to discuss following types of column based charts. Basic Column chart. Grouped Column chart. Column chart having column stacked over one another. Column chart with negative stack. Column Chart with data in percentage terms. A Material Design inspired column chart. Column chart with data labels. Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be useed to specify properties of each series individually. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used ComboChart class to show combination based chart. //combination chart var chart = new google.visualization.ComboChart(document.getElementById('container')); googlecharts_combination_chart.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable([ ['Fruit', 'Jane', 'John', 'Average'], ['Apples', 3, 2, 2.5], ['Oranges', 2, 3, 2.5], ['Pears', 1, 5, 3], ['Bananas', 3, 9, 6], ['Plums', 4, 2, 3] ]); // Set chart options var options = { title : 'Fruits distribution', vAxis: {title: 'Fruits'}, hAxis: {title: 'Person'}, seriesType: 'bars', series: {2: {type: 'line'}} }; // Instantiate and draw the chart. var chart = new google.visualization.ComboChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. A histogram is a chart that groups numeric data into buckets, displaying the buckets as segmented columns. They're used to depict the distribution of a dataset as how often values fall into ranges. Google Charts automatically chooses the number of buckets for you. All buckets are equal width and have a height proportional to the number of data points in the bucket. Histograms are similar to column charts in other aspects. In this section we're going to discuss following types of histogram based charts. Basic Histogram chart. Customized Color of Histrogram Chart. Customized Buckets of Histrogram Chart. Histrogram Chart having multiple series. Line charts are used to draw line based charts. In this section we're going to discuss following types of line based charts. Basic line chart. Chart with visible data points. Chart with customized background color. Chart with customized line color. Chart with customized axis and tick labels. Line charts showing crosshairs at data point on selection. Chart with customized line color. Chart with smooth curve lines. A Material Design inspired line chart. A Material Design inspired line chart with X-Axis on top of the chart. A Google Map Chart uses Google Maps API to display Map. Data values are displayed as markers on the map. Data values may be coordinates (lat-long pairs) or actual addresses. The map will be scaled accordingly so that it includes all the identified points. Basic Google Map. Map having locations specified using Latitude and Longitude. Customized Markers in Map. Organization chart helps in rendering a hierarchy of nodes, used to portray superior/subordinate relationships in an organization. For example, A family tree is a type of org chart.. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used OrgChart class to show organization based chart. //organization chart var chart = new google.visualization.OrgChart(document.getElementById('container')); googlecharts_organization_chart.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['orgchart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Name'); data.addColumn('string', 'Manager'); data.addColumn('string', 'ToolTip'); // For each orgchart box, provide the name, manager, and tooltip to show. data.addRows([ [{v:'Robert', f:'Robert<div style="color:red; font-style:italic">President</div>'},'', 'President'], [{v:'Jim', f:'Jim<div style="color:red; font-style:italic">Vice President</div>'},'Robert', 'Vice President'], ['Alice', 'Robert', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ]); // Set chart options var options = {allowHtml:true}; // Instantiate and draw the chart. var chart = new google.visualization.OrgChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Pie charts are used to draw pie based charts. In this section we're going to discuss following types of pie based charts. Basic pie chart. Donut Chart. 3D Pie chart. Pie chart with exploded slices. A sankey chart is a visualization tool and is used to depict a flow from one set of values to another. Connected objects are called nodes and the connections are called links. Sankeys are used to show a many-to-many mapping between two domains or multiple paths through a set of stages. Basic Sankey Chart. Multilevel Sankey Chart. Customized Sankey Chart. Sankey Charts, Scatter Charts, Stepped area charts, Table, Timelines, TreeMap, Trendlines are used to draw scatter based charts. In this section we're going to discuss following types of scatter based charts. Basic scatter chart. Material Scatter Chart. Material Scatter Chart having dual Y-Axis. Material Scatter Chart having X-Axis on top. A stepped area chart is a step based area chart. We're going to discuss following types of stepped area charts. Basic Stepped Area Chart. Stacked Stepped Area Chart. 100% Stacked Stepped Area Chart. Table chart helps in rendering a table which can be sorted and paged. Table cells can be formatted using format strings, or by directly inserting HTML as cell values. Numeric values are right-aligned by default; boolean values are displayed as check marks or cross marks. Users can select single rows either with the keyboard or the mouse. Column headers can be used for sorting. The header row remains fixed during scrolling. The table fires events corresponding to user interaction. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used Table class to show Table based chart. //table chart var chart = new google.visualization.Table(document.getElementById('container')); googlecharts_table_chart.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['table']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Name'); data.addColumn('number', 'Salary'); data.addColumn('boolean', 'Full Time Employee'); data.addRows([ ['Mike', {v: 10000, f: '$10,000'}, true], ['Jim', {v:8000, f: '$8,000'}, false], ['Alice', {v: 12500, f: '$12,500'}, true], ['Bob', {v: 7000, f: '$7,000'}, true] ]); var options = { showRowNumber: true, width: '100%', height: '100%' }; // Instantiate and draw the chart. var chart = new google.visualization.Table(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Timelines depicts how a set of resources are used over time. We're going to discuss following types of Timelines charts. Basic Timelines Chart Timelines Chart with data labels Timelines chart without Row Label Customized Timelines Chart TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used TreeMap class to show treemap diagram. //TreeMap chart var chart = new google.visualization.TreeMap(document.getElementById('container')); googlecharts_treemap.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript" src = "https://www.google.com/jsapi"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['treemap']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); var data = google.visualization.arrayToDataTable([ ['Location', 'Parent', 'Market trade volume (size)', 'Market increase/decrease (color)'], ['Global', null, 0, 0], ['America', 'Global', 0, 0], ['Europe', 'Global', 0, 0], ['Asia', 'Global', 0, 0], ['Australia', 'Global', 0, 0], ['Africa', 'Global', 0, 0], ['USA', 'America', 52, 31], ['Mexico', 'America', 24, 12], ['Canada', 'America', 16, -23], ['France', 'Europe', 42, -11], ['Germany', 'Europe', 31, -2], ['Sweden', 'Europe', 22, -13], ['China', 'Asia', 36, 4], ['Japan', 'Asia', 20, -12], ['India', 'Asia', 40, 63], ['Egypt', 'Africa', 21, 0], ['Congo', 'Africa', 10, 12], ['Zaire', 'Africa', 8, 10] ]); var options = { minColor: '#f00', midColor: '#ddd', maxColor: '#0d0', headerHeight: 15, fontColor: 'black', showScale: true }; // Instantiate and draw the chart. var chart = new google.visualization.TreeMap(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. A trendline is a line superimposed on a chart to reveal the overall direction of the data. Google Charts can automatically generate trendlines for Sankey Charts, Scatter Charts, Stepped area charts, Table, Timelines, TreeMap, Trendlines, Bar Charts, Column Charts, and Line Charts.. We're going to discuss following types of trendlines charts. Basic Trendlines Chart. Exponential Trendlines Chart. Polynomial Trendlines Chart. Print Add Notes Bookmark this page
[ { "code": null, "e": 2583, "s": 2261, "text": "Google Charts is a pure JavaScript based charting library meant to enhance web applications by adding interactive charting capability. It supports a wide range of charts. Charts are drawn using SVG in standard browsers like Chrome, Firefox, Safari, Inte...
Working on Git Bash - GeeksforGeeks
04 Aug, 2021 Git Bash is an application that provides Git command line experience on the Operating System. It is a command-line shell for enabling git with the command line in the system. A shell is a terminal application used to interface with an operating system through written commands. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system. In Git Bash the user interacts with the repository and git elements through the commands. Git is version-control system for tracking changes in source code during software development. It is designed for coordinating work among programmers, but it can be used to track changes in any set of files. Its goal is to increase efficiency, speed and easily manage large projects through version controlling. Every git working directory is a full-fledged repository with complete history and full version-tracking capabilities, independent of network access or a central server. Git helps the team cope up with the confusion that tends to happen when multiple people are editing the same files. Follow the steps given below to install Git Bash on Windows: Step 1: The .exe file installer for Git Bash can be downloaded from https://gitforwindows.org/Once downloaded execute that installer, following window will occur:- Step 2: Select the components that you need to install and click on the Next button. Step 3: Select how to use the Git from command-line and click on Next to begin the installation process. Step 4: Let the installation process finish to begin using Git Bash. To open Git Bash navigate to the folder where you have installed the git otherwise just simply search in your OS for git bash. cd command refers to change directory and is used to get into the desired directory. To navigate between the folders the cd command is usedSyntax: cd folder_name ls command is used to list all the files and folders in the current directory.Syntax: ls Open Git Bash and begin creating a username and email for working on Git Bash. Set your username: git config --global user.name "FIRST_NAME LAST_NAME" Set your email address: git config --global user.email "MY_NAME@example.com" Follow the steps given below to initialize your Local Repository with Git: Step 1: Make a repository on Github Step 2: Give a suitable name of your repository and create the repository Note: You can choose to initialize your git repository with a README file, and further, you can mention your project details in it. It helps people know what this repository is about. However, it’s absolutely not necessary. But if you do initialize your repo with a README file using interface provided by GitHub, then your local repository won’t have this README file. So to avoid running into a snag while trying to push your files (as in step 3 of next section), after step 5 (where you initialize your local folder as your git repository), do following to pull that file to your local folder: git pull Step 3: The following will appear after creating the repository Step 4: Open Git Bash and change the current working directory to your local project by use of cd command. Step 5: Initialize the local directory as a Git repository. git init Step 6: Stage the files for the first commit by adding them to the local repository git add . Step 7: By “git status” you can see the staged files Step 8: Commit the files that you’ve staged in your local repository. git commit -m "First commit" Now After “git status” command it can be seen that nothing to commit is left, Hence all files have been committed. Step 1: Go to Github repository and in code section copy the URL. Step 2: In the Command prompt, add the URL for your repository where your local repository will be pushed. git remote add origin repository_URL Step 3: Push the changes in your local repository to GitHub. git push origin master Here the files have been pushed to the master branch of your repository.Now in the GitHub repository, the pushed files can be seen. Suppose the files are being changed and new files are added to local repository.To save the changes in the git repository:Step 1: Changes have to be staged for the commit. git add . or git add file_name Step 2: Now commit the staged files. git commit -m "commit_name" Step 3: Push the changes. git push origin master New changes can be seen Suppose if a team is working on a project and a branch is created for every member working on the project.Hence every member will work on their branches hence every time the best branch is merged to the master branch of the project.The branches make it version controlling system and makes it very easy to maintain a project source code. Syntax: List all of the branches in your repository.git branch git branch Create a new branchgit branch branch_name git branch branch_name Safe Delete the specified branchgit branch -d branch_name git branch -d branch_name Force delete the specified branchgit branch -D branch_name git branch -D branch_name To navigate between the branches git checkout is used. To create create a new branch and switch on it: git checkout -b new_branch_name To simply switch to a branch git checkout branch_name After checkout to branch you can see a * on the current branch Now the same commit add and commit actions can be performed on this branch also. To merge a branch in any branch: First reach to the target branchgit checkout branch_name git checkout branch_name Merge the branch to target branchgit merge new_branch git merge new_branch Cloning is used to get a copy of the existing git repository.When you run the git clone command it makes the zip folder saved in your default location git clone url This command saves the directory as the default directory name of the git repositoryTo save directory name as your custom name an additional argument is to be passed for your custom name of directory git clone url custom_name When there is a situation when you forget to add some files to commit and want to undo any commit, it can be commit again using --ammend Syntax: git commit --amend To conclude it can be said that git bash is a command line platform which helps in enabling git and its elements in your system. There are a bunch of commands which are used in git bash. Git Bash is very easy to use and makes it easy to work on repositories and projects. priyaved11 Picked Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Set Git Username and Password in GitBash? Difference Between Git Push Origin and Git Push Origin Master How to Undo a Commit in Git ? Using GitHub with SSH (Secure Shell) Deleting a Local GitHub Repository How to Push Git Branch to Remote? Difference Between Git and GitHub How to Upload a Project on Github? How to Clone Android Project from GitHub in Android Studio? How to Export Eclipse projects to GitHub?
[ { "code": null, "e": 23928, "s": 23900, "text": "\n04 Aug, 2021" }, { "code": null, "e": 24405, "s": 23928, "text": "Git Bash is an application that provides Git command line experience on the Operating System. It is a command-line shell for enabling git with the command line in ...
Get JFrame window size information in Java
To get JFrame window size information, you can use the following − environment.getMaximumWindowBounds(); For Screen Size − config.getBounds() For Frame Size − frame.getSize()); The following is an example to get JFrame window size information − import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] args) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); Rectangle bounds = environment.getMaximumWindowBounds(); System.out.println("Screen Bounds = " + bounds); GraphicsDevice device = environment.getDefaultScreenDevice(); GraphicsConfiguration config = device.getDefaultConfiguration(); System.out.println("Screen Size = " + config.getBounds()); JFrame frame = new JFrame("Frame Info"); frame.setSize(500, 300); frame.setVisible(true); System.out.println("Frame Size = " + frame.getSize()); } } Screen Bounds = java.awt.Rectangle[x=0,y=0,width=1366,height=728] Screen Size = java.awt.Rectangle[x=0,y=0,width=1366,height=768] Frame Size = java.awt.Dimension[width=500,height=300]
[ { "code": null, "e": 1129, "s": 1062, "text": "To get JFrame window size information, you can use the following −" }, { "code": null, "e": 1167, "s": 1129, "text": "environment.getMaximumWindowBounds();" }, { "code": null, "e": 1185, "s": 1167, "text": "For Sc...
Training Deep Neural Networks. Deep Learning Accessories | by Ravindra Parmar | Towards Data Science
Deep neural networks are key break through in the field of computer vision and speech recognition. For the past decade, deep networks have enabled the machines to recognize images, speech and even play games at accuracy nigh impossible for humans. To achieve high level of accuracy, huge amount of data and henceforth computing power is needed to train these networks. However, despite the computational complexity involved, we can follow certain guidelines to reduce the time for training and improve model accuracy. In this article we will look through few of these techniques. The importance of data pre-processing can only be emphasized by the fact that your neural network is only as good as the input data used to train it. If important data inputs are missing, neural network may not be able to achieve desired level of accuracy. On the other side, if data is not processed beforehand, it could effect the accuracy as well as performance of the network down the lane. Mean subtraction (Zero centering) It’s the process of subtracting mean from each of the data point to make it zero-centered. Consider a case where inputs to neuron (unit) are all positive or all negative. In that case the gradient calculated during back propagation will either be positive or negative (same as sign of inputs). And hence parameter updates are only restricted to specific directions which in turn will make it inefficient to converge. Data Normalization Normalization refers to normalizing the data to make it of same scale across all dimensions. Common way to do that is to divide the data across each dimension by it’s standard deviation. However, it only makes sense if you have a reason to believe that different input features have different scales but they have equal importance to the learning algorithm. Deep neural networks are no stranger to millions or billions of parameters. The way these parameters are initialized can determine how fast our learning algorithm would converge and how accurate it might end up. The straightforward way is to initialize them all to zero. However, if we initialize weights of a layer to all zero, the gradients calculated will be same for each unit in the layer and hence update to weights would be same for all units. Consequently that layer is as good as a single logistic regression unit. Surely, we can do better by initializing the weights with some small random numbers. Isn’t it? Well, let’s analyse the fruitfulness of that hypothesis with a 10 layer deep neural network each consisting of 500 units and using tanh activation function. [Just a note on tanh activation before proceeding further]. On the left is the plot for tanh activation function. There are few important points to remember about this activation as we move along :- This activation is zero-centered. It saturates in case input is large positive number or large negative number. To start with, we initialize all weights from a standard Gaussian with zero mean and 1 e-2 standard deviation. W = 0.01 * np.random.randn(fan_in, fan_out) Unfortunately, this works well only for small networks. And to see what issues it creates for deeper networks plots are generated with various parameters. These plots depict the mean, standard deviation and activation for each layer as we go deeper into the network. Notice that mean is always around zero, which is obvious since we are using zero centered non-linearity. However, standard deviation is shrinking gradually as we go deeper into the network till it collapses to zero. This, as well, is obvious on account of the fact that we are multiplying the inputs with very small weights at each layer. Consequently, the gradients calculated would also be very small and hence update to weights will be negligible. Well not so good!!! Next let’s try initializing weights with very large numbers. To do so, let’s sample weights from standard Gaussian with zero mean and standard deviation as 1.0 (instead of 0.01). W = 1.0 * np.random.randn(fan_in, fan_out) Below are the plots showing mean, standard deviation and activation for all layers. Notice, the activation at each layer is either close to 1 or -1 since we are multiplying the inputs with very large weights and then feeding it to tanh non-linearity (squashes to range +1 to -1). Consequently, the gradients calculated would also be very close to zero as tanh saturates in these regimes (derivative is zero). Finally, the updates to weight would almost again be negligible. In practice, Xavier initialization is used for initializing the weights of all layers. The motivation behind Xavier initialization is to initialize the weights in such a way they do not end up in saturated regimes of tanh activation i.e initialize with values not too small or too large. To achieve that we scale by the number of inputs while randomly sampling from standard Gaussian. W = 1.0 * np.random.randn(fan_in, fan_out) / np.sqrt(fan_in) However, this works well with the assumption that tanh is used for activation. This would surely break in case of other activation functions for e.g — ReLu. No doubt that proper initialization is still an active area of research. This is somewhat related idea to what all we discussed till now. Remember, we normalized the input before feeding it to our network. One reason why this was done was to take into account the instability caused in the network by co-variance shift. It explains why even after learning the mapping from some input to output, we need to re-train the learning algorithm to learn the mapping from that same input to output in case data distribution of input changes. However, the issue isn’t resolved there only as data distribution could vary in deeper layers as well. Activation at each layer could result in different data distribution. Hence, to increase the stability of deep neural networks we need to normalize the data fed at each layer by subtracting the mean and dividing by the standard deviation. There’s an article that explains this in depth. One of the most common problem in training deep neural network is over-fitting. You’ll realize over-fitting in play when your network performed exceptionally well on the training data but poorly on test data. This happens as our learning algorithm tries to fit every data point in the input even if they represent some randomly sampled noise as demonstrated in figure below. Regularization helps avoid over-fitting by penalizing the weights of the network. To explain it further, consider a loss function defined for classification task over neural network as below : J(theta) - Overall objective function to minimize.n - Number of training samples.y(i) - Actual label for ith training sample.y_hat(i) - Predicted label for ith training sample.Loss - Cross entropy loss.Theta - Weights of neural network.Lambda - Regularization parameter. Notice how, regularization parameter (lambda) is used to control the effect of weights on final objective function. So, in case lambda takes a very large value, weights of the network should be close to zero so as to minimize the objective function. But as we let weights collapse to zero, we would nullify the effect of many units in the layer and hence network is no better than a single linear classifier with few logistic regression units. And unexpectedly, this will throw us in the regime known as under-fitting which is not much better than over-fitting. Clearly, we have to choose the value of lambda very carefully so that at the end our model falls into balanced category(3rd plot in the figure). In addition to what we discussed, there’s one more powerful technique to reduce over-fitting in deep neural networks known as dropout regularization. The key idea is to randomly drop units while training the network so that we are working with smaller neural network at each iteration. To drop a unit is same as to ignore those units during forward propagation or backward propagation. In a sense this prevents the network from adapting to some specific set of features. At each iteration we are randomly dropping some units from the network. And consequently, we are forcing each unit to not rely (not give high weights) on any specific set of units from previous layer as any of them could go off randomly. This way of spreading the weights eventually shrinks the weights at individual unit level similar to what we discussed in L 2 regularization. Much of the content can be attributed to cs231n.stanford.edu Please let me know through your comments any modification/improvements needed in the article.
[ { "code": null, "e": 752, "s": 172, "text": "Deep neural networks are key break through in the field of computer vision and speech recognition. For the past decade, deep networks have enabled the machines to recognize images, speech and even play games at accuracy nigh impossible for humans. To achi...
Pycharm - Understanding Basics
This chapter will discuss the basics of PyCharm and make you feel comfortable to begin working in PyCharm editor. When you launch PyCharm for the first time, you can see a welcome screen with entry points to IDE such as − Creating or opening the project Checking out the project from version control Viewing the documentation Configuring the IDE Recall that in the last chapter, we created a project named demo1 and we will be referring to the same project throughout this tutorial. Now we will start creating new files in the same project to understand the basics of PyCharm Editor. The above snapshot describes the project overview of demo1 and the options to create a new file. Let us create a new file called main.py. The code included in main.py is as follows − y = 3 def print_stuff(): print ("Calling print_stuff") print (y) z = 4 print (z) print("exiting print_stuff") print_stuff() # we call print_stuff and the program execution goes to (***) print(y) # works fine print (z) # NameError!!! The code created in the file main.py using PyCharm Editor is displayed as shown below − This code can be run within IDE environment. The basic demonstration of running a program is discussed below − Note that we have included some errors within the specified code such that console can execute the code and display output as the way it is intended to. 19 Lectures 59 mins Mustafa Mahmoud 19 Lectures 49 mins Pedro Planas Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 2099, "text": "This chapter will discuss the basics of PyCharm and make you feel comfortable to begin working in PyCharm editor." }, { "code": null, "e": 2321, "s": 2213, "text": "When you launch PyCharm for the first time, you can see a welcome sc...
Arduino - Comparison Operators
Assume variable A holds 10 and variable B holds 20 then − void loop () { int a = 9,b = 4 bool c = false; if(a == b) c = true; else c = false; if(a != b) c = true; else c = false; if(a < b) c = true; else c = false; if(a > b) c = true; else c = false; if(a <= b) c = true; else c = false; if(a >= b) c = true; else c = false; } c = false c = true c = false c = true c = false c = false 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2928, "s": 2870, "text": "Assume variable A holds 10 and variable B holds 20 then −" }, { "code": null, "e": 3329, "s": 2928, "text": "void loop () { \n int a = 9,b = 4\n bool c = false;\n if(a == b)\n c = true;\n else\n c = false;\n\n if(...
MomentJS - Plugins
Plugins are extended features added on MomentJS. MomentJS is an open source project and many plugins are found in MomentJS which are contributed by its users and available using Node.js and GitHub. This chapter discusses some of the calendars plugins and date formats plugins available in MomentJS. This section discusses two types of Calendar plugins: ISO calendar and Taiwan calendar. You can use the following command to install it with Node.js − npm install moment-isocalendar You can get the moment-isocalendar.js from GitHub − https://github.com/fusionbox/moment-isocalendar Observe the following working example with isocalendar and MomentJS − Example var m = moment().isocalendar(); Output Example var m = moment.fromIsocalendar([2018, 51, 10, 670]).format('LLLL'); Output You can use the following command to install it with Node.js − npm install moment-jalaali You can get the moment-taiwan.js from GitHub − https://github.com/bradwoo8621/moment-taiwan Observe the following working example with isocalendar and MomentJS − Example var m = moment('190/01/01', 'tYY/MM/DD'); var c = m.twYear(); Output This section discusses the following types of Date format plugins − Java dateformat parser Short date formatter Parse date format Duration format Date Range Precise Range You can use the following command to install it with Node.js − You can get the moment-jdateformatparser.js from GitHub − https://github.com/MadMG/moment-jdateformatparser Observe the following working example for moment-jdateformatparser and MomentJS − Example var m = moment().formatWithJDF("dd.MM.yyyy"); Output The JavaScript file for shortdateformat can be fetched from GitHub − Syntax moment().short(); The display looks like as shown in the table here − You can take the script for momentshort from GitHub link given above. Example var a = moment().subtract(8, 'hours').short(); var b = moment().add(1, 'hour').short(true); Output If you want to remove the suffix ago or in, you can pass true to short(tru. You can use the following command to install it with Node.js − npm install moment-parseformat Example var a = moment.parseFormat('Friday 2018 27 april 10:28:10'); Output Observe that the output shows that whatever parameters (date/ time) is given to the parseFormat, it gives the format of the date as shown above. You can use the following command to install duration format on Node.js − The repository for duration format is available here − https://github.com/jsmreese/moment-duration-format Let us see a working example with duration format − Example var a = moment.duration(969, "minutes").format("h:mm:ss"); Output This adds more details to the duration on moment created. You can use the following command to install date range on Node.js − npm install moment-range Example window['moment-range'].extendMoment(moment); var start = new Date(2012, 0, 15); var end = new Date(2012, 4, 23); var range = moment.range(start, end); console.log(range.start._d); console.log(range.end._d); Output Precise range will display the exact date difference in date, time and in human readable format. You can use the following command to install precise range on Node.js − npm install moment-precise-range-plugin Example var a = moment("1998-01-01 09:00:00").preciseDiff("2011-03-04 18:05:06"); Output Print Add Notes Bookmark this page
[ { "code": null, "e": 2158, "s": 1960, "text": "Plugins are extended features added on MomentJS. MomentJS is an open source project and many plugins are found in MomentJS which are contributed by its users and available using Node.js and GitHub." }, { "code": null, "e": 2259, "s": 215...
Stack toArray(T[]) method in Java with Example - GeeksforGeeks
24 Dec, 2018 The toArray(T[]) method method of Stack class in Java is used to form an array of the same elements as that of the Stack. It returns an array containing all of the elements in this Stack in the correct order; the run-time type of the returned array is that of the specified array. If the Stack fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the run time type of the specified array and the size of this Stack.If the Stack fits in the specified array with room to spare (i.e., the array has more elements than the Stack), the element in the array immediately following the end of the Stack is set to null. (This is useful in determining the length of the Stack only if the caller knows that the Stack does not contain any null elements.) Syntax: Object[] arr1 = Stack.toArray(arr[]) Parameters: The method accepts one parameter arr[] which is the array into which the elements of the Stack are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. Return Value: The method returns an array containing the elements similar to the Stack. Exception: The method might throw two types of exception: ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the Stack. NullPointerException: If the array is Null, then this exception is thrown. Below program illustrates the working of the Stack.toArray(arr[]) method. Program 1: When array is of the size of Stack // Java code to illustrate toArray(arr[]) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("For"); stack.add("Geeks"); // Displaying the Stack System.out.println("The Stack: " + stack); // Creating the array and using toArray() String[] arr = new String[5]; arr = stack.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }} The Stack: [Welcome, To, Geeks, For, Geeks] The arr[] is: Welcome To Geeks For Geeks Program 2: When array is less than the size of Stack // Java code to illustrate toArray(arr[]) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("For"); stack.add("Geeks"); // Displaying the Stack System.out.println("The Stack: " + stack); // Creating the array and using toArray() String[] arr = new String[1]; arr = stack.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }} The Stack: [Welcome, To, Geeks, For, Geeks] The arr[] is: Welcome To Geeks For Geeks Program 3: When array is more than the size of Stack // Java code to illustrate toArray(arr[]) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("For"); stack.add("Geeks"); // Displaying the Stack System.out.println("The Stack: " + stack); // Creating the array and using toArray() String[] arr = new String[10]; arr = stack.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }} The Stack: [Welcome, To, Geeks, For, Geeks] The arr[] is: Welcome To Geeks For Geeks null null null null null Program 4: To demonstrate NullPointerException // Java code to illustrate toArray(arr[]) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("For"); stack.add("Geeks"); // Displaying the Stack System.out.println("The Stack: " + stack); try { // Creating the array String[] arr = null; // using toArray() // Since arr is null // Hence exception will be thrown arr = stack.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); } catch (Exception e) { System.out.println("Exception: " + e); } }} The Stack: [Welcome, To, Geeks, For, Geeks] Exception: java.lang.NullPointerException Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java
[ { "code": null, "e": 24201, "s": 24173, "text": "\n24 Dec, 2018" }, { "code": null, "e": 24985, "s": 24201, "text": "The toArray(T[]) method method of Stack class in Java is used to form an array of the same elements as that of the Stack. It returns an array containing all of the...
Count pairs from two BSTs whose sum is equal to a given value x - GeeksforGeeks
06 May, 2022 Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 x = 16 Output : 3 The pairs are: (5, 11), (6, 10) and (8, 8) Method 1: For each node value a in BST 1, search the value (x – a) in BST 2. If value found then increment the count. For searching a value in BST, refer this post. Time complexity: O(n1 * h2), here n1 is number of nodes in first BST and h2 is height of second BST. Method 2: Traverse BST 1 from smallest value to node to largest. This can be achieved with the help of iterative inorder traversal. Traverse BST 2 from largest value node to smallest. This can be achieved with the help of reverse inorder traversal. Perform these two traversals simultaneously. Sum up the corresponding node’s value from both the BSTs at a particular instance of traversals. If sum == x, then increment count. If x > sum, then move to the inorder successor of the current node of BST 1, else move to the inorder predecessor of the current node of BST 2. Perform these operations until either of the two traversals gets completed. C++ Java Python3 C# Javascript // C++ implementation to count pairs from two// BSTs whose sum is equal to a given value x#include <bits/stdc++.h>using namespace std; // structure of a node of BSTstruct Node { int data; Node* left, *right;}; // function to create and return a node of BSTNode* getNode(int data){ // allocate space for the node Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->left = new_node->right = NULL;} // function to count pairs from two BSTs// whose sum is equal to a given value xint countPairs(Node* root1, Node* root2, int x){ // if either of the tree is empty if (root1 == NULL || root2 == NULL) return 0; // stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 stack<Node*> st1, st2; Node* top1, *top2; int count = 0; // the loop will break when either of two // traversals gets completed while (1) { // to find next node in inorder // traversal of BST 1 while (root1 != NULL) { st1.push(root1); root1 = root1->left; } // to find next node in reverse // inorder traversal of BST 2 while (root2 != NULL) { st2.push(root2); root2 = root2->right; } // if either gets empty then corresponding // tree traversal is completed if (st1.empty() || st2.empty()) break; top1 = st1.top(); top2 = st2.top(); // if the sum of the node's is equal to 'x' if ((top1->data + top2->data) == x) { // increment count count++; // pop nodes from the respective stacks st1.pop(); st2.pop(); // insert next possible node in the // respective stacks root1 = top1->right; root2 = top2->left; } // move to next possible node in the // inorder traversal of BST 1 else if ((top1->data + top2->data) < x) { st1.pop(); root1 = top1->right; } // move to next possible node in the // reverse inorder traversal of BST 2 else { st2.pop(); root2 = top2->left; } } // required count of pairs return count;} // Driver program to test aboveint main(){ // formation of BST 1 Node* root1 = getNode(5); /* 5 */ root1->left = getNode(3); /* / \ */ root1->right = getNode(7); /* 3 7 */ root1->left->left = getNode(2); /* / \ / \ */ root1->left->right = getNode(4); /* 2 4 6 8 */ root1->right->left = getNode(6); root1->right->right = getNode(8); // formation of BST 2 Node* root2 = getNode(10); /* 10 */ root2->left = getNode(6); /* / \ */ root2->right = getNode(15); /* 6 15 */ root2->left->left = getNode(3); /* / \ / \ */ root2->left->right = getNode(8); /* 3 8 11 18 */ root2->right->left = getNode(11); root2->right->right = getNode(18); int x = 16; cout << "Pairs = " << countPairs(root1, root2, x); return 0;} // Java implementation to count pairs from two// BSTs whose sum is equal to a given value ximport java.util.Stack;public class GFG { // structure of a node of BST static class Node { int data; Node left, right; // constructor public Node(int data) { this.data = data; left = null; right = null; } } static Node root1; static Node root2; // function to count pairs from two BSTs // whose sum is equal to a given value x static int countPairs(Node root1, Node root2, int x) { // if either of the tree is empty if (root1 == null || root2 == null) return 0; // stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 //stack<Node*> st1, st2; Stack<Node> st1 = new Stack<>(); Stack<Node> st2 = new Stack<>(); Node top1, top2; int count = 0; // the loop will break when either of two // traversals gets completed while (true) { // to find next node in inorder // traversal of BST 1 while (root1 != null) { st1.push(root1); root1 = root1.left; } // to find next node in reverse // inorder traversal of BST 2 while (root2 != null) { st2.push(root2); root2 = root2.right; } // if either gets empty then corresponding // tree traversal is completed if (st1.empty() || st2.empty()) break; top1 = st1.peek(); top2 = st2.peek(); // if the sum of the node's is equal to 'x' if ((top1.data + top2.data) == x) { // increment count count++; // pop nodes from the respective stacks st1.pop(); st2.pop(); // insert next possible node in the // respective stacks root1 = top1.right; root2 = top2.left; } // move to next possible node in the // inorder traversal of BST 1 else if ((top1.data + top2.data) < x) { st1.pop(); root1 = top1.right; } // move to next possible node in the // reverse inorder traversal of BST 2 else { st2.pop(); root2 = top2.left; } } // required count of pairs return count; } // Driver program to test above public static void main(String args[]) { // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; System.out.println("Pairs = " + countPairs(root1, root2, x)); }}// This code is contributed by Sumit Ghosh # Python3 implementation to count pairs# from two BSTs whose sum is equal to a# given value x # Structure of a node of BSTclass getNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to count pairs from two BSTs# whose sum is equal to a given value xdef countPairs(root1, root2, x): # If either of the tree is empty if (root1 == None or root2 == None): return 0 # Stack 'st1' used for the inorder # traversal of BST 1 # stack 'st2' used for the reverse # inorder traversal of BST 2 st1 = [] st2 = [] count = 3 # The loop will break when either # of two traversals gets completed while (1): # To find next node in inorder # traversal of BST 1 while (root1 != None): st1.append(root1) root1 = root1.left # To find next node in reverse # inorder traversal of BST 2 while (root2 != None): st2.append(root2) root2 = root2.right # If either gets empty then corresponding # tree traversal is completed if (len(st1) or len(st2)): break top1 = st1[len(st1) - 1] top2 = st2[len(st2) - 1] # If the sum of the node's is equal to 'x' if ((top1.data + top2.data) == x): # Increment count count += 1 # Pop nodes from the respective stacks st1.remove(st1[len(st1) - 1]) st2.remove(st2[len(st2) - 1]) # Insert next possible node in the # respective stacks root1 = top1.right root2 = top2.left # Move to next possible node in the # inorder traversal of BST 1 elif ((top1.data + top2.data) < x): st1.remove(st1[len(st1) - 1]) root1 = top1.right # Move to next possible node in the # reverse inorder traversal of BST 2 else: st2.remove(st2[len(st2) - 1]) root2 = top2.left # Required count of pairs return count # Driver codeif __name__ == '__main__': # Formation of BST 1 ''' 5 / \ 3 7 / \ / \ 2 4 6 8 ''' root1 = getNode(5) root1.left = getNode(3) root1.right = getNode(7) root1.left.left = getNode(2) root1.left.right = getNode(4) root1.right.left = getNode(6) root1.right.right = getNode(8) # Formation of BST 2 ''' 10 / \ 6 15 / \ / \ 3 8 11 18 ''' root2 = getNode(10) root2.left = getNode(6) root2.right = getNode(15) root2.left.left = getNode(3) root2.left.right = getNode(8) root2.right.left = getNode(11) root2.right.right = getNode(18) x = 16 print("Pairs = ", countPairs(root1, root2, x)) # This code is contributed by bgangwar59 // C# implementation to count pairs from two// BSTs whose sum is equal to a given value xusing System;using System.Collections.Generic; // C# implementation to count pairs from two// BSTs whose sum is equal to a given value xpublic class GFG{ // structure of a node of BST public class Node { public int data; public Node left, right; // constructor public Node(int data) { this.data = data; left = null; right = null; } } public static Node root1; public static Node root2; // function to count pairs from two BSTs // whose sum is equal to a given value x public static int countPairs(Node root1, Node root2, int x) { // if either of the tree is empty if (root1 == null || root2 == null) { return 0; } // stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 //stack<Node*> st1, st2; Stack<Node> st1 = new Stack<Node>(); Stack<Node> st2 = new Stack<Node>(); Node top1, top2; int count = 0; // the loop will break when either of two // traversals gets completed while (true) { // to find next node in inorder // traversal of BST 1 while (root1 != null) { st1.Push(root1); root1 = root1.left; } // to find next node in reverse // inorder traversal of BST 2 while (root2 != null) { st2.Push(root2); root2 = root2.right; } // if either gets empty then corresponding // tree traversal is completed if (st1.Count == 0 || st2.Count == 0) { break; } top1 = st1.Peek(); top2 = st2.Peek(); // if the sum of the node's is equal to 'x' if ((top1.data + top2.data) == x) { // increment count count++; // pop nodes from the respective stacks st1.Pop(); st2.Pop(); // insert next possible node in the // respective stacks root1 = top1.right; root2 = top2.left; } // move to next possible node in the // inorder traversal of BST 1 else if ((top1.data + top2.data) < x) { st1.Pop(); root1 = top1.right; } // move to next possible node in the // reverse inorder traversal of BST 2 else { st2.Pop(); root2 = top2.left; } } // required count of pairs return count; } // Driver program to test above public static void Main(string[] args) { // formation of BST 1 root1 = new Node(5); // 5 root1.left = new Node(3); // / \ root1.right = new Node(7); // 3 7 root1.left.left = new Node(2); // / \ / \ root1.left.right = new Node(4); // 2 4 6 8 root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); // 10 root2.left = new Node(6); // / \ root2.right = new Node(15); // 6 15 root2.left.left = new Node(3); // / \ / \ root2.left.right = new Node(8); // 3 8 11 18 root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; Console.WriteLine("Pairs = " + countPairs(root1, root2, x)); }} // This code is contributed by Shrikant13 <script> // JavaScript implementation to count pairs// from two BSTs whose sum is equal to a// given value x // Structure of a node of BSTclass getNode{ constructor(data){ this.data = data this.left = null this.right = null } } // Function to count pairs from two BSTs// whose sum is equal to a given value xfunction countPairs(root1, root2, x){ // If either of the tree is empty if (root1 == null || root2 == null) return 0 // Stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 let st1 = [] let st2 = [] let count = 3 // The loop will break when either // of two traversals gets completed while (1){ // To find next node in inorder // traversal of BST 1 while (root1 != null){ st1.push(root1) root1 = root1.left } // To find next node in reverse // inorder traversal of BST 2 while (root2 != null){ st2.push(root2) root2 = root2.right } // If either gets empty then corresponding // tree traversal is completed if (st1.length || st2.length) break top1 = st1[st1.length - 1] top2 = st2[st2.length - 1] // If the sum of the node's is equal to 'x' if ((top1.data + top2.data) == x){ // Increment count count += 1 // Pop nodes from the respective stacks st1.pop() st2.pop() // Insert next possible node in the // respective stacks root1 = top1.right root2 = top2.left } // Move to next possible node in the // inorder traversal of BST 1 else if ((top1.data + top2.data) < x){ st1.pop() root1 = top1.right } // Move to next possible node in the // reverse inorder traversal of BST 2 else{ st2.pop() root2 = top2.left } } // Required count of pairs return count} // Driver code // Formation of BST 1 // 5 // / \ // 3 7 // / \ / \ // 2 4 6 8 let root1 = new getNode(5) root1.left = new getNode(3)root1.right = new getNode(7)root1.left.left = new getNode(2)root1.left.right = new getNode(4)root1.right.left = new getNode(6)root1.right.right = new getNode(8) // Formation of BST 2 // 10 // / \ // 6 15 // / \ / \ // 3 8 11 18 let root2 = new getNode(10)root2.left = new getNode(6)root2.right = new getNode(15)root2.left.left = new getNode(3)root2.left.right = new getNode(8)root2.right.left = new getNode(11)root2.right.right = new getNode(18) let x = 16 document.write("Pairs = ", countPairs(root1, root2, x),"</br>") // This code is contributed by shinjanpatra </script> Pairs = 3 Time Complexity: O(n1 + n2) Auxiliary Space: O(h1 + h2) Where h1 is height of first tree and h2 is height of second tree Method 3 : Recursive approach to solving this question.Traverse the BST1 and for each node find the diff i.e. (x – root1.data) in BST2 and increment the count. Recursive approach to solving this question. Traverse the BST1 and for each node find the diff i.e. (x – root1.data) in BST2 and increment the count. Java Python3 C# Javascript // Java implementation to count pairs from two// BSTs whose sum is equal to a given value ximport java.util.Stack;public class GFG { // structure of a node of BST static class Node { int data; Node left, right; // constructor public Node(int data) { this.data = data; left = null; right = null; } } static Node root1; static Node root2; // function to count pairs from two BSTs // whose sum is equal to a given value x public static int pairCount = 0; public static void traverseTree(Node root1, Node root2, int sum) { if (root1 == null || root2 == null) { return; } traverseTree(root1.left, root2, sum); traverseTree(root1.right, root2, sum); int diff = sum - root1.data; findPairs(root2, diff); } private static void findPairs(Node root2, int diff) { if (root2 == null) { return; } if (diff > root2.data) { findPairs(root2.right, diff); } else { findPairs(root2.left, diff); } if (root2.data == diff) { pairCount++; } } public static int countPairs(Node root1, Node root2, int sum) { traverseTree(root1, root2, sum); return pairCount; } // Driver program to test above public static void main(String args[]) { // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; System.out.println("Pairs = " + countPairs(root1, root2, x)); }}// This code is contributed by Sujit Panda # Python implementation to count pairs from two# BSTs whose sum is equal to a given value x # structure of a node of BSTclass Node: # constructor def __init__(self,data): self.data = data self.left = None self.right = None root1,root2 = None,None # def to count pairs from two BSTs# whose sum is equal to a given value xpairCount = 0def traverseTree(root1, root2, sum): if (root1 == None or root2 == None): return traverseTree(root1.left, root2, sum) traverseTree(root1.right, root2, sum) diff = sum - root1.data findPairs(root2, diff) def findPairs(root2 , diff): global pairCount if (root2 == None): return if (diff > root2.data) : findPairs(root2.right, diff) else : findPairs(root2.left, diff) if (root2.data == diff): pairCount += 1 def countPairs(root1, root2, sum): global pairCount traverseTree(root1, root2, sum) return pairCount # Driver program to test above # formation of BST 1root1 = Node(5) root1.left = Node(3) root1.right = Node(7)root1.left.left = Node(2)root1.left.right = Node(4) root1.right.left = Node(6)root1.right.right = Node(8) # formation of BST 2root2 = Node(10) root2.left = Node(6) root2.right = Node(15)root2.left.left = Node(3)root2.left.right = Node(8) root2.right.left = Node(11)root2.right.right = Node(18) x = 16print(f"Pairs = {countPairs(root1, root2, x)}") # This code is contributed by shinjanpatra // C# implementation to count pairs from two// BSTs whose sum is equal to a given value xusing System; using System.Collections.Generic;public class GFG { // structure of a node of BST public class Node { public int data; public Node left, right; // constructor public Node(int data) { this.data = data; left = null; right = null; } } static Node root1; static Node root2; // function to count pairs from two BSTs // whose sum is equal to a given value x public static int pairCount = 0; public static void traverseTree(Node root1, Node root2, int sum) { if (root1 == null || root2 == null) { return; } traverseTree(root1.left, root2, sum); traverseTree(root1.right, root2, sum); int diff = sum - root1.data; findPairs(root2, diff); } private static void findPairs(Node root2, int diff) { if (root2 == null) { return; } if (diff > root2.data) { findPairs(root2.right, diff); } else { findPairs(root2.left, diff); } if (root2.data == diff) { pairCount++; } } public static int countPairs(Node root1, Node root2, int sum) { traverseTree(root1, root2, sum); return pairCount; } // Driver program to test above public static void Main(String []args) { // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; Console.WriteLine("Pairs = " + countPairs(root1, root2, x)); }} // This code is contributed by Rajput-Ji <script>// javascript implementation to count pairs from two// BSTs whose sum is equal to a given value x // structure of a node of BST class Node { // constructor constructor(data) { this.data = data; this.left = null; this.right = null; } } var root1; var root2; // function to count pairs from two BSTs // whose sum is equal to a given value x var pairCount = 0; function traverseTree(root1, root2, sum) { if (root1 == null || root2 == null) { return; } traverseTree(root1.left, root2, sum); traverseTree(root1.right, root2, sum); var diff = sum - root1.data; findPairs(root2, diff); } function findPairs(root2 , diff) { if (root2 == null) { return; } if (diff > root2.data) { findPairs(root2.right, diff); } else { findPairs(root2.left, diff); } if (root2.data == diff) { pairCount++; } } function countPairs(root1, root2, sum) { traverseTree(root1, root2, sum); return pairCount; } // Driver program to test above // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); var x = 16; document.write("Pairs = " + countPairs(root1, root2, x)); // This code is contributed by Rajput-Ji</script> Pairs = 3 Method 4 : Using BinarySearch Tree Iterator ( A more general way of doing this ) Create two class one as BSTIterator1 and other as BSTIterator2. These two class corresponds to inOrder and reverse inOrder traversal respectively. Each class will have three methods – hasNext : will return true when traversal is not yet completed next : will move the pointer to the next node peek : will return current node in the traversal After creating two such classes, simple run the iterator while both have next node and find the sum. If sum == x, increment the next pointer of iterator1 and iterator2 and if sum > x ,increment the next pointer of iterator2 else increment the next pointer of iterator1 i.e when sum < x. Below is the code in java. Java C# import java.util.*;class Node{ int data; Node left, right; public Node(int data){ this.data = data; this.left = null; this.right = null; }}// inorder successor iteratorclass BSTIterator1{ Stack<Node> s1 = new Stack<>(); Node root1; boolean hasPeeked = false; public BSTIterator1(Node root){ this.root1 = root; } public boolean hasNext(){ if(!s1.isEmpty() || root1!=null) return true; return false; } public Node peek(){ if(!hasNext()) return null; while(root1!=null){ s1.push(root1); root1 = root1.left; hasPeeked = true; } return s1.peek(); } public int next(){ if(!hasNext()) return -1; if(!hasPeeked) peek(); hasPeeked = false; root1 = s1.pop(); Node temp = root1; root1 = root1.right; return temp.data; }}// inorder predecessor iteratorclass BSTIterator2{ Stack<Node> s1 = new Stack<>(); Node root1; boolean hasPeeked = false; public BSTIterator2(Node root){ this.root1 = root; } public boolean hasNext(){ if(!s1.isEmpty() || root1!=null) return true; return false; } public Node peek(){ if(!hasNext()) return null; while(root1!=null){ s1.push(root1); root1 = root1.right; hasPeeked = true; } return s1.peek(); } public int next(){ if(!hasNext()) return -1; if(!hasPeeked) peek(); hasPeeked = false; root1 = s1.pop(); Node temp = root1; root1 = root1.left; return temp.data; }}class GfG{ public static int countPairs(Node r1, Node r2, int x) { BSTIterator1 it1 = new BSTIterator1(r1); BSTIterator2 it2 = new BSTIterator2(r2); int count = 0; while(it1.hasNext() && it2.hasNext()){ Node n1 = it1.peek(); Node n2 = it2.peek(); int sum = n1.data+n2.data; if(sum == x){ count++; it1.next(); it2.next(); } else if(sum > x){ it2.next(); }else{ it1.next(); } } return count; } // Driver program to test above public static void main(String args[]) { Node root1, root2; // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; System.out.println("Pairs = " + countPairs(root1, root2, x)); }} using System;using System.Collections.Generic; public class Node{ public int data; public Node left, right; public Node(int data){ this.data = data; this.left = null; this.right = null; }} // inorder successor iteratorpublic class BSTIterator1{ public Stack<Node> s1 = new Stack<Node>(); public Node root1; public bool hasPeeked = false; public BSTIterator1(Node root){ this.root1 = root; } public bool hasNext(){ if(s1.Count != 0 || root1 != null) return true; return false; } public Node peek(){ if(!hasNext()) return null; while(root1 != null){ s1.Push(root1); root1 = root1.left; hasPeeked = true; } return s1.Peek(); } public int next(){ if(!hasNext()) return -1; if(!hasPeeked) peek(); hasPeeked = false; root1 = s1.Pop(); Node temp = root1; root1 = root1.right; return temp.data; }}// inorder predecessor iteratorpublic class BSTIterator2{ public Stack<Node> s1 = new Stack<Node>(); public Node root1; public bool hasPeeked = false; public BSTIterator2(Node root){ this.root1 = root; } public bool hasNext(){ if(s1.Count != 0 || root1 != null) return true; return false; } public Node peek(){ if(!hasNext()) return null; while(root1 != null){ s1.Push(root1); root1 = root1.right; hasPeeked = true; } return s1.Peek(); } public int next(){ if(!hasNext()) return -1; if(!hasPeeked) peek(); hasPeeked = false; root1 = s1.Pop(); Node temp = root1; root1 = root1.left; return temp.data; }}public class GfG{ public static int countPairs(Node r1, Node r2, int x) { BSTIterator1 it1 = new BSTIterator1(r1); BSTIterator2 it2 = new BSTIterator2(r2); int count = 0; while(it1.hasNext() && it2.hasNext()){ Node n1 = it1.peek(); Node n2 = it2.peek(); int sum = n1.data+n2.data; if(sum == x){ count++; it1.next(); it2.next(); } else if(sum > x){ it2.next(); }else{ it1.next(); } } return count; } // Driver program to test above public static void Main(String []args) { Node root1, root2; // formation of BST 1 root1 = new Node(5); /* 5 */ root1.left = new Node(3); /* / \ */ root1.right = new Node(7); /* 3 7 */ root1.left.left = new Node(2); /* / \ / \ */ root1.left.right = new Node(4); /* 2 4 6 8 */ root1.right.left = new Node(6); root1.right.right = new Node(8); // formation of BST 2 root2 = new Node(10); /* 10 */ root2.left = new Node(6); /* / \ */ root2.right = new Node(15); /* 6 15 */ root2.left.left = new Node(3); /* / \ / \ */ root2.left.right = new Node(8); /* 3 8 11 18 */ root2.right.left = new Node(11); root2.right.right = new Node(18); int x = 16; Console.WriteLine("Pairs = " + countPairs(root1, root2, x)); }} // This code is contributed by Rajput-Ji Pairs = 3 Time Complexity: O(n1 + n2) Auxiliary Space: O(h1 + h2) Where h1 is height of first tree and h2 is height of second tree shrikanth13 bgangwar59 sky8214 sujitpanda gabaa406 devaxdu Rajput-Ji shinjanpatra Traversal Binary Search Tree Traversal Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorted Array to Balanced BST Red-Black Tree | Set 2 (Insert) Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Find the node with minimum value in a Binary Search Tree Advantages of BST over Hash Table Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Binary Tree and Binary Search Tree Binary Tree to Binary Search Tree Conversion Inorder predecessor and successor for a given key in BST
[ { "code": null, "e": 26623, "s": 26595, "text": "\n06 May, 2022" }, { "code": null, "e": 26783, "s": 26623, "text": "Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x." ...
p5.js | select() Function - GeeksforGeeks
29 Jan, 2020 The select() function is used to search an element in the page with the given id, class or tag name and return it as a p5.element. It has a syntax similar to the CSS selector. An optional parameter is available that can be used to search within a given element. This method only returns the first element if multiple elements exist on the page that matches the selector. Note: The DOM node of the element can be accessed using the .elt property. Syntax: select(name, [container]) Parameters: This function accept two parameters as mentioned above and described below: name: It is a string which denotes the id, class or tag name of the element that has to be searched. container: It is an optional parameter which denotes an element to search. Return Value: When the given element is successfully found, it returns a p5.element that contains the node. Otherwise, it returns null. Below examples illustrates the select() function in p5.js: Example 1: function setup() { createCanvas(650, 50); textSize(20); text("Click the mouse to select the paragraph" + " element and change its position.", 0, 20); para1 = createP("This is paragraph 1"); para2 = createP("This is paragraph 2"); para3 = createP("This is paragraph 3");} function mouseClicked() { // Select the first // paragraph element selectedP = select("p"); // Change position to 200, 20 selectedP.position(200, 20);} Output: Example 2: function setup() { createCanvas(650, 300); textSize(20); text("Click the mouse once to select the"+ " canvas and change its color.", 0, 20); } function mouseClicked() { // Select the first // canvas element selectedCanvas = select("canvas"); // Get the DOM node using .elt and // change background color to green selectedCanvas.elt.style.backgroundColor = "green";} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/select JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? 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": 44937, "s": 44909, "text": "\n29 Jan, 2020" }, { "code": null, "e": 45308, "s": 44937, "text": "The select() function is used to search an element in the page with the given id, class or tag name and return it as a p5.element. It has a syntax similar to the C...
TypeScript | String Prototype Property - GeeksforGeeks
18 Jun, 2020 The Prototype Property() in TypeScript which is used to add properties and methods to an object. Syntax: string.prototype Return Value: This method does not returns any value. Below examples illustrate the String Prototype property in TypeScriptExample 1: JavaScript function Person(name:string, job:string, yearOfBirth:number) { this.name= name; this.job= job; this.yearOfBirth= yearOfBirth; } // Driver code var emp = new Person("Smith", "ABC",12214) // This will show Person's prototype property. console.log(emp.prototype); Output: Example #2: JavaScript function Person(name:string, job:string, yearOfBirth:number) { this.name= name; this.job= job; this.yearOfBirth= yearOfBirth; } // Driver code var emp = new Person("Smith", "ABC",12214) // This will show Person's prototype property. Person.prototype.email = "abc@123.com"; console.log("Person's name: " + emp.name); console.log("Person's Email ID: " + emp.email); Output: TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25727, "s": 25699, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25832, "s": 25727, "text": "The Prototype Property() in TypeScript which is used to add properties and methods to an object. Syntax:" }, { "code": null, "e": 25850, "s": 25832...
Base class pointer pointing to derived class object - GeeksforGeeks
23 Aug, 2021 Pointer is a data type that stores the address of other data types. The pointer of Base Class pointing different object of derived class: Approach: A derived class is a class which takes some properties from its base class. It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible. To access the variable of the base class, base class pointer will be used. So, a pointer is type of base class, and it can access all, public function and variables of base class since pointer is of base class, this is known as binding pointer. In this pointer base class is owned by base class but points to derived class object. Same works with derived class pointer, values is changed. Below is the C++ program to illustrate the implementation of the base class pointer pointing to the derived class: C++ // C++ program to illustrate the// implementation of the base class// pointer pointing to derived class#include <iostream>using namespace std; // Base Classclass BaseClass {public: int var_base; // Function to display the base // class members void display() { cout << "Displaying Base class" << " variable var_base: " << var_base << endl; }}; // Class derived from the Base Classclass DerivedClass : public BaseClass {public: int var_derived; // Function to display the base // and derived class members void display() { cout << "Displaying Base class" << "variable var_base: " << var_base << endl; cout << "Displaying Derived " << " class variable var_derived: " << var_derived << endl; }}; // Driver Codeint main(){ // Pointer to base class BaseClass* base_class_pointer; BaseClass obj_base; DerivedClass obj_derived; // Pointing to derived class base_class_pointer = &obj_derived; base_class_pointer->var_base = 34; // Calling base class member function base_class_pointer->display(); base_class_pointer->var_base = 3400; base_class_pointer->display(); DerivedClass* derived_class_pointer; derived_class_pointer = &obj_derived; derived_class_pointer->var_base = 9448; derived_class_pointer->var_derived = 98; derived_class_pointer->display(); return 0;} Output: Displaying Base class variable var_base: 34 Displaying Base class variable var_base: 3400 Displaying Base classvariable var_base: 9448 Displaying Derived class variable var_derived: 98 Conclusion: A pointer to derived class is a pointer of base class pointing to derived class, but it will hold its aspect. This pointer of base class will be able to temper functions and variables of its own class and can still point to derived class object. arorakashish0911 parasharashi02 hgaur701 C++-Class and Object Pointers C++ C++ Programs Technical Scripter Pointers CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25367, "s": 25339, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25435, "s": 25367, "text": "Pointer is a data type that stores the address of other data types." }, { "code": null, "e": 25505, "s": 25435, "text": "The pointer of Base Cl...
How to check if a browser tab is currently active or not? - GeeksforGeeks
08 Mar, 2021 Sometimes we need to check if the current browser tab is active or not. When you open YouTube and watch a movie for a long in the browser then the auto screen timeout doesn’t work but when you open Facebook, after some time the screen turns off due to the screen timeout of the device. So how does YouTube know if a tab is active? In this article, we will discuss this. To achieve this functionality we have the following methods. The page Visibility API Window.onfocus and Window.onblur The Page Visibility API: It lets the developers know if the current tab is currently active or not. When the user switches to another tab or minimizes the window, then the pagevisibilitychange event gets triggered. This API added these properties to the document object. document.hidden: It returns true when the page is not in focus and returns false when the page is in focus. document.visibilityState: It returns the current visibility state of the document. It returns these states as “hidden“, “visible”, “unloaded”, and “prerender”. hidden means the current tab is not in focus, visible means the current tab is in focus, unloaded means the current tab is about to close, prerender means the page has been loaded but the user has not viewed the page. It is a read-only property, you cannot modify it. document.onvisibilitychange: An eventListener when the visibilitychange event is fired. Example: In this example, we are creating a popup that gets closed automatically when the user moves to another tab or minimizes the window. HTML <!DOCTYPE html><html> <head> <style type="text/css" media="screen"> .popup { height: 300px; width: 300px; margin: 0 auto; border: 1px solid; box-shadow: 7px 7px 167px 1px #585858; display: none; justify-content: center; align-items: center; margin-top: 100px; background: #f1f1f1; font-family: cursive; } </style> </head> <body> <center> <h1>Sample popup</h1> <button id="btn">click me</button> </center> <div class="popup"> <p>I am a PopUp</p> </div> <script> let btn = document.querySelector("#btn"); let pop = document.querySelector(".popup"); btn.addEventListener("click", () => { pop.style.display = "flex"; }); document.addEventListener("visibilitychange", () => { pop.style.display = "none"; }); </script> </body></html> Output : The onfocus/onblur Method: This events are also used to know if the element is visible or not. But there is a problem with this method, If you are opening a small window on top of your current window, then the onblur event gets called, and when you close that small window, the onfocus method does not get called and the window remains in a blur state. Example: In this example, we are showing a popup that automatically disappears when the user focuses out the current tab. HTML <!DOCTYPE html><html> <head> <style type="text/css" media="screen"> .popup { height: 300px; width: 300px; margin: 0 auto; border: 1px solid; box-shadow: 7px 7px 167px 1px #585858; display: none; justify-content: center; align-items: center; margin-top: 100px; background: #f1f1f1; font-family: cursive; } </style> </head> <body> <center> <h1>Sample popup</h1> <button id="btn">click me</button> </center> <div class="popup"> <p>I am a PopUp</p> </div> <script> let btn = document.querySelector("#btn"); let pop = document.querySelector(".popup"); btn.addEventListener("click", () => { pop.style.display = "flex"; }); window.onblur = () => (pop.style.display = "none"); window.onfocus = () => alert("onfocus event called"); </script> </body></html> Output: When the user changes its focus to another window and then again comes back to the original window, it alerts saying the following message. onfocus event called javascript-dataView JavaScript-Questions JavaScript 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n08 Mar, 2021" }, { "code": null, "e": 26877, "s": 26545, "text": "Sometimes we need to check if the current browser tab is active or not. When you open YouTube and watch a movie for a long in the browser then the auto screen time...
C# | Char.IsLetterOrDigit() Method - GeeksforGeeks
01 Feb, 2019 In C#, Char.IsLetterOrDigit() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a letter or decimal digit. Valid letters and decimal digits will be the members of the UnicodeCategory: UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter, OtherLetter, or DecimalDigitNumber category. This method can be overloaded by passing different type and number of arguments to it. Char.IsLetterOrDigit(Char) MethodChar.IsLetterOrDigit(String, Int32) Method Char.IsLetterOrDigit(Char) Method Char.IsLetterOrDigit(String, Int32) Method This method is used to check whether the specified Unicode character matches any letter or decimal digit. If it matches then it returns True otherwise return False. Syntax: public static bool IsLetterOrDigit(char ch); Parameter: ch: It is required Unicode character of System.char type which is to be checked. Return Type: The method returns True, if it successfully matches any Unicode letter or decimal digit, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsLetterOrDigit(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if G is a // letter or decimal digit char ch1 = 'G'; result = Char.IsLetterOrDigit(ch1); Console.WriteLine(result); // checking if '@' is a // letter or decimal digit char ch2 = '@'; result = Char.IsLetterOrDigit(ch2); Console.WriteLine(result); }} True False This method is used to check whether the specified string at specified position matches with any letter or decimal digit. If it matches then it returns True otherwise returns False. Syntax: public static bool IsLetterOrDigit(string str, int index); Parameters: Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32. Return Type: The method returns True if it successfully matches any letter or decimal digit at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean. Exceptions: If the value of str is null then this method will give ArgumentNullException. If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException. Example: // C# program to illustrate the// Char.IsLetterOrDigit(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for letter or decimal digit // in a string at desired position string str1 = "Geeks46orGeeks"; result = Char.IsLetterOrDigit(str1, 5); Console.WriteLine(result); // checking for letter or decimal digit // in a string at a desired position string str2 = "geeks%forgeeks"; result = Char.IsLetterOrDigit(str2, 5); Console.WriteLine(result); }} True False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsLetterOrDigit?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# Dictionary with examples C# | Delegates C# | Arrays of Strings C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C#
[ { "code": null, "e": 25277, "s": 25249, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25714, "s": 25277, "text": "In C#, Char.IsLetterOrDigit() is a System.Char struct method which is used to check whether a Unicode character can be categorized as a letter or decimal digit. Va...
bokeh.plotting.figure.asterisk() function in Python - GeeksforGeeks
17 Jun, 2020 Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. The asterisk() function in plotting module of bokeh library is used to Configure and add Asterisk glyphs to this Figure. Syntax: asterisk(x, y, size=4, angle=0.0, *, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, tags=[], **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is the x-coordinates for the center of the markers. y: This parameter is the y-coordinates for the center of the markers. size: This parameter is the size (diameter) values for the markers in screen space units. angle: This parameter is the angles to rotate the markers. fill_alpha: This parameter is the fill alpha values for the markers. fill_color: This parameter is the fill color values for the markers. line_alpha: This parameter is the line alpha values for the markers with default value of 1.0 . line_cap: This parameter is the line cap values for the markers with default value of butt. line_color: This parameter is the line color values for the markers with default value of black. line_dash: This parameter is the line dash values for the markers with default value of []. line_dash_offset: This parameter is the line dash offset values for the markers with default value of 0. line_join: This parameter is the line join values for the markers with default value of bevel. line_width: This parameter is the line width values for the markers with default value of 1. mode: This parameter can be one of three values : [“before”, “after”, “center”]. name: This parameter is the user-supplied name for this model. tags: This parameter is the user-supplied values for this model. Other Parameters: These parameters are **kwargs that are described below: alpha: This parameter is used to set all alpha keyword arguments at once. color: This parameter is used to to set all color keyword arguments at once. legend_field: This parameter is the name of a column in the data source that should be used or the grouping. legend_group: This parameter is the name of a column in the data source that should be used or the grouping. legend_label: This parameter is the legend entry is labeled with exactly the text supplied here. muted: This parameter contains the bool value. name: This parameter is the optional user-supplied name to attach to the renderer. source: This parameter is the user-supplied data source. view: This parameter is the view for filtering the data source. visible: This parameter contains the bool value. x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates. y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates. level: This parameter specify the render level order for this glyph. Return: This method return the GlyphRenderer value. Below examples illustrate the bokeh.plotting.figure.asterisk() function in bokeh.plotting:Example 1: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300)plot.asterisk(x =[1, 2, 3], y =[3, 2, 1], size = 30, color ="green", alpha = 0.6) show(plot) Output: Example 2: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show N = 9x = np.linspace(-2, 2, N)y = x**2sizes = np.linspace(20, 50, N) plot = figure(plot_width = 300, plot_height = 300)plot.asterisk(x = x, y = y, size = sizes, color ="green", alpha = 0.6, line_width = 3) show(plot) Output: Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26163, "s": 26135, "text": "\n17 Jun, 2020" }, { "code": null, "e": 26497, "s": 26163, "text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like ...
How to sort by value in PySpark? - GeeksforGeeks
18 Jul, 2021 In this article, we are going to sort by value in PySpark. Creating RDD for demonstration: Python3 # importing modulefrom pyspark.sql import SparkSession, Row # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # create 2 Rows with 3 columnsdata = Row(First_name="Sravan", Last_name="Kumar", age=23),Row(First_name="Ojaswi", Last_name="Pinkey", age=16),Row(First_name="Rohith", Last_name="Devi", age=7) # create row on rddrdd = spark.sparkContext.parallelize(data) # display datardd.collect() Output: [Row(First_name='Sravan', Last_name='Kumar', age=23), Row(First_name='Ojaswi', Last_name='Pinkey', age=16), Row(First_name='Rohith', Last_name='Devi', age=7)] sortBy() is used to sort the data by value efficiently in pyspark. It is a method available in rdd. Syntax: rdd.sortBy(lambda expression) It uses a lambda expression to sort the data based on columns. lambda expression: lambda x: x[column_index] Example 1: Sort the data by values based on column 1 Python3 # sort the data by values based on column 1rdd.sortBy(lambda x: x[0]).collect() Output: [Row(First_name='Ojaswi', Last_name='Pinkey', age=16), Row(First_name='Rohith', Last_name='Devi', age=7), Row(First_name='Sravan', Last_name='Kumar', age=23)] Example 2: Sort data based on column 2 values Python3 # sort the data by values based on column 2rdd.sortBy(lambda x: x[2]).collect() Output: [Row(First_name='Rohith', Last_name='Devi', age=7), Row(First_name='Ojaswi', Last_name='Pinkey', age=16), Row(First_name='Sravan', Last_name='Kumar', age=23)] It is the method available in RDD, this is used to sort values based on values in a particular column. Syntax: rdd.takeOrdered(n,lambda expression) where, n is the total rows to be displayed after sorting Sort values based on a particular column using takeOrdered function Python3 # sort values based on# column 1 using takeOrdered functionprint(rdd.takeOrdered(3,lambda x: x[0])) # sort values based on# column 3 using takeOrdered functionprint(rdd.takeOrdered(3,lambda x: x[2])) Output: [Row(First_name=’Ojaswi’, Last_name=’Pinkey’, age=16), Row(First_name=’Rohith’, Last_name=’Devi’, age=7), Row(First_name=’Sravan’, Last_name=’Kumar’, age=23)] [Row(First_name=’Rohith’, Last_name=’Devi’, age=7), Row(First_name=’Ojaswi’, Last_name=’Pinkey’, age=16), Row(First_name=’Sravan’, Last_name=’Kumar’, age=23)] Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n18 Jul, 2021" }, { "code": null, "e": 25596, "s": 25537, "text": "In this article, we are going to sort by value in PySpark." }, { "code": null, "e": 25628, "s": 25596, "text": "Creating RDD for demonstration:...
Number of ways to traverse an N-ary tree - GeeksforGeeks
27 Apr, 2022 Given an n-ary tree, count number of ways to traverse an n-ary (or a Directed Acyclic Graph) tree starting from the root vertex.Suppose we have a given N-ary tree as shown below. Now we have to find the number of ways of traversing the whole tree starting from the root vertex. There can be many such ways. Some of them are listed below.1) N->M->K->J->B->F->D->E->C->H->I->L->A (kind-of depth first traversal). 2) A->B->F->D->E->K->J->G->C->H->I->N->M->L (level order traversal) 3) ......... 4) ......... . . . and so on....We strongly recommend you to minimize your browser and try this yourself first.The count of all ways to traverse is the product of factorials of the number of children of each node. Refer to the below figure for clear understanding- Here,‘A’ has four children, so 4! permutations possible ‘B’ has two children, so 2! permutations possible ‘F’ has no children, so 0! permutations possible ..... And so onHence all such ways are- 4 ! * 2 ! * 0 ! * 1 ! * 3 ! * 2 ! * 0 ! * 0 ! * 0 ! * 0 ! * 1 ! * 0 ! * 0 ! = 576 wayThat’s a huge number of ways and among them only few proves to be useful, like- inorder, level-order, preorder, postorder (arranged according to the popularity of these traversals) C++ Python3 Javascript // C++ program to find the number of ways to traverse a// n-ary tree starting from the root node#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node{ char key; vector<Node *> child;}; // Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;} // Utility Function to find factorial of given numberint factorial(int n){ if (n == 0) return 1; return n*factorial(n-1);} // Function to calculate the number of ways of traversing// the n-ary starting from root.// This function is just a modified breadth-first search.// We can use a depth-first search too.int calculateWays(Node * root){ int ways = 1; // Initialize result // If the tree is empty there is no way of traversing // the tree. if (root == NULL) return 0; // Create a queue and enqueue root to it. queue<Node *>q; q.push(root); // Level order traversal. while (!q.empty()) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); // The number of ways is the product of // factorials of number of children of each node. ways = ways*(factorial(p->child.size())); // Enqueue all childrent of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); } return(ways);} // Driver programint main(){ /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ Node *root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[2]->child).push_back(newNode('L')); cout << calculateWays(root); ; return 0;} # Python program to find the# number of ways to traverse a# n-ary tree starting from the root node class Node: def __init__(self,key): self.child = [] self.key = key # Utility function to create a new tree nodedef newNode(key): temp = Node(key) return temp # Utility Function to find factorial of given numberdef factorial(n): if (n == 0): return 1 return n*factorial(n-1) # Function to calculate the number of ways of traversing# the n-ary starting from root.# self function is just a modified breadth-first search.# We can use a depth-first search too.def calculateWays(root): ways = 1 # Initialize result # If the tree is empty there is no way of traversing # the tree. if (root == None): return 0 # Create a queue and enqueue root to it. q = [] q.append(root) # Level order traversal. while (len(q) > 0): # Dequeue an item from queue and print it p = q[0] q = q[1:] # The number of ways is the product of # factorials of number of children of each node. ways = ways*(factorial(len(p.child))) # Enqueue all childrent of the dequeued item for i in range(len(p.child)): q.append(p.child[i]) return(ways) # Let us create below tree# * A# * / / \ \# * B F D E# * / \ | /|\# * K J G C H I# * /\ \# * N M L root = newNode('A');(root.child).append(newNode('B'));(root.child).append(newNode('F'));(root.child).append(newNode('D'));(root.child).append(newNode('E'));(root.child[0].child).append(newNode('K'));(root.child[0].child).append(newNode('J'));(root.child[2].child).append(newNode('G'));(root.child[3].child).append(newNode('C'));(root.child[3].child).append(newNode('H'));(root.child[3].child).append(newNode('I'));(root.child[0].child[0].child).append(newNode('N'));(root.child[0].child[0].child).append(newNode('M'));(root.child[3].child[2].child).append(newNode('L')); print(calculateWays(root)) <script> // JavaScript program to find the // number of ways to traverse a // n-ary tree starting from the root node class Node { constructor(key) { this.child = []; this.key = key; } } // Utility function to create a new tree node function newNode(key) { let temp = new Node(key); return temp; } // Utility Function to find factorial of given number function factorial(n) { if (n == 0) return 1; return n*factorial(n-1); } // Function to calculate the number of ways of traversing // the n-ary starting from root. // This function is just a modified breadth-first search. // We can use a depth-first search too. function calculateWays(root) { let ways = 1; // Initialize result // If the tree is empty there is no way of traversing // the tree. if (root == null) return 0; // Create a queue and enqueue root to it. let q = []; q.push(root); // Level order traversal. while (q.length > 0) { // Dequeue an item from queue and print it let p = q[0]; q.shift(); // The number of ways is the product of // factorials of number of children of each node. ways = ways*(factorial(p.child.length)); // Enqueue all childrent of the dequeued item for (let i=0; i< p.child.length; i++) q.push(p.child[i]); } return(ways); } /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ let root = newNode('A'); (root.child).push(newNode('B')); (root.child).push(newNode('F')); (root.child).push(newNode('D')); (root.child).push(newNode('E')); (root.child[0].child).push(newNode('K')); (root.child[0].child).push(newNode('J')); (root.child[2].child).push(newNode('G')); (root.child[3].child).push(newNode('C')); (root.child[3].child).push(newNode('H')); (root.child[3].child).push(newNode('I')); (root.child[0].child[0].child).push(newNode('N')); (root.child[0].child[0].child).push(newNode('M')); (root.child[3].child[2].child).push(newNode('L')); document.write(calculateWays(root)); </script> Output: 576 Time Complexity: We visit each node once during the level order traversal and take O(n) time to compute factorial for every node. Total time taken is O(Nn) where N = number of nodes in the n-ary tree. We can optimize the solution to work in O(N) time by per-computing factorials of all numbers from 1 to n.Auxiliary Space : Since we are only using a queue and a structure for every node, so overall space complexity is also O(N).Common Pitfalls: Since, products of factorials can tend to grow very huge, so it may overflow. It is preferable to use data types like- unsigned long long int in C/C++, as the number of ways can never be a negative number. In Java and Python there are Big Integer to take care of overflows. YouTubeGeeksforGeeks507K subscribersNumber of ways to traverse an N-ary tree | 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 / 7:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Uv1W80vMVC4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above suresh07 sagartomar9927 simmytarika5 shinjanpatra n-ary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree BFS vs DFS for Binary Tree Deletion in a Binary Tree
[ { "code": null, "e": 26243, "s": 26215, "text": "\n27 Apr, 2022" }, { "code": null, "e": 26423, "s": 26243, "text": "Given an n-ary tree, count number of ways to traverse an n-ary (or a Directed Acyclic Graph) tree starting from the root vertex.Suppose we have a given N-ary tree ...
How can we write main as a class in C++? - GeeksforGeeks
07 Feb, 2020 As it is already known that main() method is the entry point in any program in C++, hence creating a class named “main” is a challenge and is generally not possible. But this article explains how to write a class named “main” in C++. What happens when we try to write a class named main?Writing a class named main is not allowed generally in C++, as the compiler gets confused it with main() method. Hence when we write the main class, creating its object will lead to error as it won’t consider the ‘main’ as a class name.Example: // C++ program to declare// a class with name main #include <bits/stdc++.h>using namespace std; // Class named mainclass main { public: void print() { cout << "GFG"; }}; // Driver codeint main(){ // Creating an object of class main main obj; // Calling the print() method // of class main obj.print();} Output: Compilation Error in CPP code :- prog.cpp: In function 'int main()': prog.cpp:17:10: error: expected ';' before 'obj' main obj; ^ prog.cpp:18:5: error: 'obj' was not declared in this scope obj.print(); ^ How to successfully create a class named main?When the class name is main, it is compulsory to use keyword class or struct to declare objects. Example: // C++ program to declare// a class with name main #include <bits/stdc++.h>using namespace std; // Class named mainclass main { public: void print() { cout << "GFG"; }}; // Driver codeint main(){ // Creating an object of class main // Add keyword class ahead of main class main obj; // Calling the print() method // of class main obj.print();} GFG How to write a constructor or destructor named main?Writing a constructor or destructor named main is not a problem, as it means the class name must be main. We have already discussed how to make a class named main above. Example: // C++ program to declare// a class with name main #include <bits/stdc++.h>using namespace std; // Class named mainclass main { public: // Constructor main() { cout << "In constructor main()\n"; } // Destructor ~main() { cout << "In destructor main()"; } void print() { cout << "GFG\n"; }}; // Driver codeint main(){ // Creating an object of class main // Add keyword class ahead of main class main obj; // Calling the print() method // of class main obj.print();} In constructor main() GFG In destructor main() cpp-main C++ Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25799, "s": 25771, "text": "\n07 Feb, 2020" }, { "code": null, "e": 26033, "s": 25799, "text": "As it is already known that main() method is the entry point in any program in C++, hence creating a class named “main” is a challenge and is generally not possibl...
<mat-label> in Angular Material - GeeksforGeeks
05 Feb, 2021 Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-label is similar to labels which we use in normal HTML forms. But the advantage with mat-label is that it has pre-defined CSS style classes and animations defined in it. Installation syntax: ng add @angular/material Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import ‘MatFormFieldModule’ from ‘@angular/material/form-field’ in the app.module.ts file. Now we need to use <mat-label> tag with respective label name inside the <mat-form-field> tag. Below is an example on how to use <mat-label> tag inside <mat-form-field> Once done with the above steps then serve or start the project. Project Structure: It will look like the following. Code Implementation: app.module.ts: Javascript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatFormFieldModule } from '@angular/material/form-field'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatFormFieldModule, BrowserAnimationsModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } app.component.html: HTML <mat-form-field appearance="legacy"> <mat-label>Mat Label Example</mat-label> <input matInput placeholder="Placeholder"></mat-form-field> Output: Angular-material Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26290, "s": 26262, "text": "\n05 Feb, 2021" }, { "code": null, "e": 26757, "s": 26290, "text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to in...
Sorting a Queue without extra space - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Interleave the first half of the queue with second half Sorting a Queue without extra space Sort the Queue using Recursion Check if a queue can be sorted into another queue using a stack Reverse individual words Reverse words in a given string Print words of a string in reverse order Different methods to reverse a string in C/C++ std::reverse() in C++ How to reverse a Vector using STL in C++? What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? How to pass a 2D array as a parameter in C? Multidimensional Arrays in C / C++ Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue using Stacks Queue in Python Interleave the first half of the queue with second half Sorting a Queue without extra space Sort the Queue using Recursion Check if a queue can be sorted into another queue using a stack Reverse individual words Reverse words in a given string Print words of a string in reverse order Different methods to reverse a string in C/C++ std::reverse() in C++ How to reverse a Vector using STL in C++? What are the default values of static variables in C? Understanding “volatile” qualifier in C | Set 2 (Examples) Const Qualifier in C Initialization of static variables in C Understanding “register” keyword in C Understanding “extern” keyword in C Storage Classes in C Static Variables in C Memory Layout of C Programs How to deallocate memory without using free() in C? Difference Between malloc() and calloc() with Examples Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() How to dynamically allocate a 2D array in C? How to pass a 2D array as a parameter in C? Multidimensional Arrays in C / C++ Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue Interface In Java Queue using Stacks Queue in Python Difficulty Level : Medium Given a queue with random elements, we need to sort it. We are not allowed to use extra space. The operations allowed on queue are : enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called push().dequeue() : Removes an item from front of queue. In C++ STL queue, this function is called pop().isEmpty() : Checks if a queue is empty. In C++ STL queue, this function is called empty(). enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called push(). dequeue() : Removes an item from front of queue. In C++ STL queue, this function is called pop(). isEmpty() : Checks if a queue is empty. In C++ STL queue, this function is called empty(). Examples : Input : A queue with elements 11 5 4 21 Output : Modified queue with following elements 4 5 11 21 Input : A queue with elements 3 2 1 2 Output : Modified queue with following elements 1 2 2 3 If we are allowed extra space, then we can simply move all items of queue to an array, then sort the array and finally move array elements back to queue.How to do without extra space? The idea: on every pass on the queue, we seek for the next minimum index. To do this we dequeue and enqueue elements until we find the next minimum. In this operation the queue is not changed at all. After we have found the minimum index, we dequeue and enqueue elements from the queue except for the minimum index, after we finish the traversal in the queue we insert the minimum to the rear of the queue. We keep on this until all minimums are pushed all way long to the front and the queue becomes sorted. On every next seeking for the minimum, we exclude seeking on the minimums that have already sorted. We repeat this method n times. At first we seek for the maximum, because on every pass we need find the next minimum, so we need to compare it with the largest element in the queue.Illustration: Input : ------------- 11 5 4 21 min index = 2 ------------- ------------- 11 5 21 4 after inserting 4 ------------- ------------- 11 5 21 4 min index = 1 ------------- ------------- 11 21 4 5 after inserting 5 ------------- ------------- 11 21 4 5 min index = 0 ------------- ------------- 21 4 5 11 after inserting 11 ------------- ------------- 21 4 5 11 min index = 0 ------------- ------------- 4 5 11 21 after inserting 21 ------------- Output : 4 5 11 21 C++ Java Python3 C# Javascript // C++ program to implement sorting a// queue data structure#include <bits/stdc++.h>using namespace std; // Queue elements after sortedIndex are// already sorted. This function returns// index of minimum element from front to// sortedIndexint minIndex(queue<int> &q, int sortedIndex){ int min_index = -1; int min_val = INT_MAX; int n = q.size(); for (int i=0; i<n; i++) { int curr = q.front(); q.pop(); // This is dequeue() in C++ STL // we add the condition i <= sortedIndex // because we don't want to traverse // on the sorted part of the queue, // which is the right part. if (curr <= min_val && i <= sortedIndex) { min_index = i; min_val = curr; } q.push(curr); // This is enqueue() in // C++ STL } return min_index;} // Moves given minimum element to rear of// queuevoid insertMinToRear(queue<int> &q, int min_index){ int min_val; int n = q.size(); for (int i = 0; i < n; i++) { int curr = q.front(); q.pop(); if (i != min_index) q.push(curr); else min_val = curr; } q.push(min_val);} void sortQueue(queue<int> &q){ for (int i = 1; i <= q.size(); i++) { int min_index = minIndex(q, q.size() - i); insertMinToRear(q, min_index); }} // driver codeint main(){ queue<int> q; q.push(30); q.push(11); q.push(15); q.push(4); // Sort queue sortQueue(q); // Print sorted queue while (q.empty() == false) { cout << q.front() << " "; q.pop(); } cout << endl; return 0;} // Java program to implement sorting a// queue data structureimport java.util.LinkedList;import java.util.Queue;class GFG{ // Queue elements after sortIndex are // already sorted. This function returns // index of minimum element from front to // sortIndex public static int minIndex(Queue<Integer> list, int sortIndex) { int min_index = -1; int min_value = Integer.MAX_VALUE; int s = list.size(); for (int i = 0; i < s; i++) { int current = list.peek(); // This is dequeue() in Java STL list.poll(); // we add the condition i <= sortIndex // because we don't want to traverse // on the sorted part of the queue, // which is the right part. if (current <= min_value && i <= sortIndex) { min_index = i; min_value = current; } list.add(current); } return min_index;} // Moves given minimum element // to rear of queue public static void insertMinToRear(Queue<Integer> list, int min_index) { int min_value = 0; int s = list.size(); for (int i = 0; i < s; i++) { int current = list.peek(); list.poll(); if (i != min_index) list.add(current); else min_value = current; } list.add(min_value); } public static void sortQueue(Queue<Integer> list) { for(int i = 1; i <= list.size(); i++) { int min_index = minIndex(list,list.size() - i); insertMinToRear(list, min_index); } } //Driver function public static void main (String[] args) { Queue<Integer> list = new LinkedList<Integer>(); list.add(30); list.add(11); list.add(15); list.add(4); //Sort Queue sortQueue(list); //print sorted Queue while(list.isEmpty()== false) { System.out.print(list.peek() + " "); list.poll(); } }} // This code is contributed by akash1295 # Python3 program to implement sorting a# queue data structurefrom queue import Queue # Queue elements after sortedIndex are# already sorted. This function returns# index of minimum element from front to# sortedIndexdef minIndex(q, sortedIndex): min_index = -1 min_val = 999999999999 n = q.qsize() for i in range(n): curr = q.queue[0] q.get() # This is dequeue() in C++ STL # we add the condition i <= sortedIndex # because we don't want to traverse # on the sorted part of the queue, # which is the right part. if (curr <= min_val and i <= sortedIndex): min_index = i min_val = curr q.put(curr) # This is enqueue() in # C++ STL return min_index # Moves given minimum element to# rear of queuedef insertMinToRear(q, min_index): min_val = None n = q.qsize() for i in range(n): curr = q.queue[0] q.get() if (i != min_index): q.put(curr) else: min_val = curr q.put(min_val) def sortQueue(q): for i in range(1, q.qsize() + 1): min_index = minIndex(q, q.qsize() - i) insertMinToRear(q, min_index) # Driver codeif __name__ == '__main__': q = Queue() q.put(30) q.put(11) q.put(15) q.put(4) # Sort queue sortQueue(q) # Print sorted queue while (q.empty() == False): print(q.queue[0], end = " ") q.get() # This code is contributed by PranchalK // C# program to implement// sorting a queue data structureusing System;using System.Collections.Generic; class GFG{ // Queue elements after sorted // Index are already sorted. // This function returns index // of minimum element from front // to sortedIndex static int minIndex(ref Queue<int> q, int sortedIndex) { int min_index = -1; int min_val = int.MaxValue; int n = q.Count; for (int i = 0; i < n; i++) { int curr = q.Peek(); q.Dequeue(); // This is dequeue() // in C++ STL // we add the condition // i <= sortedIndex because // we don't want to traverse // on the sorted part of the // queue, which is the right part. if (curr <= min_val && i <= sortedIndex) { min_index = i; min_val = curr; } q.Enqueue(curr); // This is enqueue() // in C++ STL } return min_index; } // Moves given minimum // element to rear of queue static void insertMinToRear(ref Queue<int> q, int min_index) { int min_val = 0; int n = q.Count; for (int i = 0; i < n; i++) { int curr = q.Peek(); q.Dequeue(); if (i != min_index) q.Enqueue(curr); else min_val = curr; } q.Enqueue(min_val); } static void sortQueue(ref Queue<int> q) { for (int i = 1; i <= q.Count; i++) { int min_index = minIndex(ref q, q.Count - i); insertMinToRear(ref q, min_index); } } // Driver Code static void Main() { Queue<int> q = new Queue<int>(); q.Enqueue(30); q.Enqueue(11); q.Enqueue(15); q.Enqueue(4); // Sort queue sortQueue(ref q); // Print sorted queue while (q.Count != 0) { Console.Write(q.Peek() + " "); q.Dequeue(); } Console.WriteLine(); }}// This code is contributed by// Manish Shaw(manishshaw1) <script> // / JavaScript program to implement sorting a// / queue data structure // / Queue elements after sortedIndex are// / already sorted. This function returns// / index of minimum element from front to// / sortedIndexfunction minIndex(q, sortedIndex){ let min_index = -1 let min_val = 999999999999 let n = q.length for(let i = 0; i < n; i++) { let curr = q.shift() // q.get() / This is dequeue() in C++ STL // / we add the condition i <= sortedIndex // / because we don't want to traverse // / on the sorted part of the queue, // / which is the right part. if (curr <= min_val && i <= sortedIndex){ min_index = i min_val = curr } q.push(curr) // This is enqueue() in // / C++ STL } return min_index} // / Moves given minimum element to// / rear of queuefunction insertMinToRear(q, min_index){ let min_val = 0 let n = q.length for(let i=0;i<n;i++){ let curr = q.shift() if (i != min_index) q.push(curr) else min_val = curr } q.push(min_val)} function sortQueue(q){ for(let i=1;i<q.length+1;i++){ let min_index = minIndex(q, q.length - i) insertMinToRear(q, min_index) }} // / Driver code let q = []q.push(30)q.push(11)q.push(15)q.push(4) // / Sort queuesortQueue(q) // / Print sorted queuewhile (q.length > 0){ document.write(q.shift()," ")} // This code is contributed by shinjanpatra </script> Output: 4 11 15 30 Time complexity of this algorithm is O(n^2). Extra space needed is O(1). YouTubeGeeksforGeeks508K subscribersSorting a queue without extra space | 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 / 9:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OcQyfkpA0YY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> akash1295 manishshaw1 PranchalKatiyar simmytarika5 shinjanpatra cpp-queue Queue Sorting Sorting Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue | Set 1 (Introduction and Array Implementation) Priority Queue | Set 1 (Introduction) LRU Cache Implementation Queue - Linked List Implementation Circular Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data Sc...
How to locate a particular module in Python? - GeeksforGeeks
06 Jun, 2021 In this article, we will see how to locate a particular module in Python? Locating a module means finding the directory from which the module is imported. When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current directory. If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories. If that also fails python checks the installation-dependent list of directories configured at the time Python is installed. The sys.path contains the list of the current directory, PYTHONPATH, and the installation-dependent default. We will discuss how to use this and other methods to locate the module in this article. For a pure python module we can locate its source by module_name.__file__. This will return the location where the module’s .py file exists. To get the directory we can use os.path.dirname() method in os module. For example if we want to know the location of ‘random’ module using this method we will type the following in the python file Python # importing random moduleimport random # importing the os moduleimport os # storing the path of modules file # in variable file_pathfile_path = random.__file__ # storing the directory in dir variabledir = os.path.dirname(file_path) # printing the directoryprint(dir) Output: C;\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib For this method, we will be using the sys module. The sys.path variable of sys module contains all the directories which will be searched for modules at runtime. So by knowing these directories we can manually check where our particular module exists. To implement this we have to write the following in python shell:- Python # importing sys moduleimport sys # importing sys.pathprint(sys.path) This will return the list of all directories which will be searched for the module at runtime. Output: [‘/home’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’, ‘/usr/lib/python2.7/lib-tk’, ‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’, ‘/usr/local/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages’] In the python shell after we import some modules we can get various information about the module using help(module_name). For example, if we want to know the location of the module os using this method we will type the following in python shell Python # importing os moduleimport os # printing help(os)print(help(os)) Under various information, we will find a heading with the name FILE below which the location of the module will be present. Output: .... /various other informartion/ .... FILE c:\Users\lenovo\appdata\local\programs\python\python39\lib\os.py We can also use the inspect module in python to locate a module. We will use inspect.getfile() method of inspect module to get the path. This method will take the module’s name as an argument and will return its path. For example, if we want to find the directory of the os module using this method we will write the following code: Python # importing random moduleimport inspect # importing the os moduleimport os # printing the file path of os moduleprint(inspect.getfile(os)) Output: C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\os.py Picked python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25788, "s": 25537, "text": "In this article, we will see how to locate a particular module in Python? Locating a module means finding the directory from which the module is imported. When we ...
Templates in GoLang - GeeksforGeeks
16 Jul, 2020 Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates: text/template html/template There are mainly 3 parts of a template which are as follows: They are data evaluations, control structures like loops or functions. Actions are delimited by {{ and }} where the root element is shown up by using dot operator(.) within braces, {{.}}. These actions control how the final output will look.To place the value of a field of current struct object, prefix the field name by a dot operator(.) within curly braces like {{.FieldName}}. The data which is evaluated inside it is called pipeline. if-else construct can also be used within a template. For example, to execute a template only when the condition is true, we can use the following syntax: {{if .condition}} temp_0 {{else if .condition}} temp_1 {{else}} temp_2 {{end}} This will execute the first template, temp_0, if the first condition is true if the second condition holds true, then the second template, temp_1, will execute, else the third template, temp_2, will execute. Iterations can also be used within a template using the range action. Syntax for looping within a template is: {{range .List}} temp_0 {{else}} temp_1 {{end}} Here List should be an array, map or slice which if has length 0, then template temp_1 will be executed, else it iterates through the elements on List. The input format for a template should be of a UTF-8-encoded format. Any other text outside is printed as it is to the standard output. The predefined variable os.Stdout refers to the standard output to print out the merged data. The Execute() function takes any value which implements the Writer interface and applies a parsed template to the specified data object. Example 1: // Golang program to illustrate the// concept of text/templatespackage main import ( "os" "fmt" "text/template") // declaring a structtype Student struct{ // declaring fields which are // exported and accessible // outside of package as they // begin with a capital letter Name string Marks int64} // main functionfunc main() { // defining an object of struct std1 := Student{"Vani", 94} // "New" creates a new template // with name passed as argument tmp1 := template.New("Template_1") // "Parse" parses a string into a template tmp1, _ = tmp1.Parse("Hello {{.Name}}, your marks are {{.Marks}}%!") // standard output to print merged data err := tmp1.Execute(os.Stdout, std1) // if there is no error, // prints the output if err != nil { fmt.Println(err) }} Output: Hello Vani, your marks are 94%! The package template “html/template” provides same interface to the “text/template” but rather having a text output, it implements data-driven templates for generating HTML output. This HTML output is safe against any external code injection. Example 2: “index.html” file: <!DOCTYPE html><html><head><title>Results</title></head><body><h1>Hello, {{.Name}}, ID number: {{.Id}}</h1><p> You have scored {{.Marks}}!<p></body></html> “main.go” file: // Golang program to illustrate the// concept of html/templatespackage main import ( "html/template" "os") // declaring structtype Student struct { // defining struct fields Name string Marks int Id string} // main functionfunc main() { // defining struct instance std1 := Student{"Vani", 94, "20024"} // Parsing the required html // file in same directory t, err := template.ParseFiles("index.html") // standard output to print merged data err = t.Execute(os.Stdout, std1)} Output: <!DOCTYPE html><html><head><title>Page Title</title></head><body><h1>Hello, Vani, ID number: 20024</h1><p> You have scored 94!<p></body></html> Akanksha_Rai Golang-Misc Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Strings in Golang Time Durations in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Loops in Go Language Defer Keyword in Golang Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25847, "s": 25703, "text": "Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates:" }, { "code...
JavaScript | Pipeline Operator - GeeksforGeeks
12 Jun, 2020 The JavaScript Pipeline Operator ( |> ) is used to pipe the value of an expression into a function. This operator makes chained functions more readable. This function is called using ( |> ) operator and whatever value is used on the pipeline operator is passed as an argument to the function. The functions are placed in the order in which they operate on the argument. Syntax: expression |> function Using the Pipeline Operator: As the Pipeline Operator is an experimental feature and currently in stage 1 proposal, there is no support for currently available browsers and therefore is also not included in Node. However, one can use the Babel (JavaScript Compiler) to use it. Steps: Before moving ahead, make sure that Node.js is installed. Create a directory on your desktop (say pipeline-operator) and within that directory create a JavaScript file (say main.js). Navigate to the directory and initialize a package.json file that contains relevant information about project and its dependencies. npm init npm init Install babel in order to use operator. A pipeline operator is not currently part of JavaScript language, babel is used to compile the code so that it can be understood by Node.npm install @babel/cli @babel/core @babel/plugin-proposal-pipeline-operator npm install @babel/cli @babel/core @babel/plugin-proposal-pipeline-operator To direct babel about the compilation of the code properly, a file named .babelrc is created with the following lines:{ "plugins": [ [ "@ babel/plugin-proposal-pipeline-operator", { "proposal" : "minimal" } ] ] } { "plugins": [ [ "@ babel/plugin-proposal-pipeline-operator", { "proposal" : "minimal" } ] ] } Add a start script to package.json file which will run babel:"start" : "babel main.js --out-file output.js && node output.js" "start" : "babel main.js --out-file output.js && node output.js" Run the code: npm start npm start Example: Javascript // JavaScript Code (main.js) function add(x) { return x + 10;} function subtract(x) { return x - 5;} // Without pipeline operatorlet val1 = add(subtract(add(subtract(10))));console.log(val1); // Using pipeline operator // First 10 is passed as argument to subtract// function then returned value is passed to// add function then value we get is passed to// subtract and then the value we get is again// passed to add functionlet val2 = 10 |> subtract |> add |> subtract |> add;console.log(val2); Output: 20 20 JavaScript-Misc Picked JavaScript Web Technologies 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": "\n12 Jun, 2020" }, { "code": null, "e": 26915, "s": 26545, "text": "The JavaScript Pipeline Operator ( |> ) is used to pipe the value of an expression into a function. This operator makes chained functions more readable. This funct...
First-Order Inductive Learner (FOIL) Algorithm - GeeksforGeeks
26 Nov, 2020 Prerequisites: Predicates and Quantifiers, Learn-One-Rule, Sequential Covering Algorithm Before getting into the FOIL Algorithm, let us understand the meaning of first-order rules and the various terminologies involved in it. First-Order Logic: All expressions in first-order logic are composed of the following attributes: constants — e.g. tyler, 23, avariables — e.g. A, B, Cpredicate symbols — e.g. male, father (True or False values only)function symbols — e.g. age (can take on any constant as a value)connectives — e.g. ∧, ∨, ¬, →, ←quantifiers — e.g. ∀, ∃ constants — e.g. tyler, 23, a variables — e.g. A, B, C predicate symbols — e.g. male, father (True or False values only) function symbols — e.g. age (can take on any constant as a value) connectives — e.g. ∧, ∨, ¬, →, ← quantifiers — e.g. ∀, ∃ Term: It can be defined as any constant, variable or function applied to any term. e.g. age(bob) Literal: It can be defined as any predicate or negated predicate applied to any terms. e.g. female(sue), father(X, Y) It has 3 types: Ground Literal — a literal that contains no variables. e.g. female(sue) Positive Literal — a literal that does not contain a negated predicate. e.g. female(sue) Negative Literal — a literal that contains a negated predicate. e.g. father(X,Y) Clause – It can be defined as any disjunction of literals whose variables are universally quantified. where, M1, M2, ...,Mn --> literals (with variables universally quantified) V --> Disjunction (logical OR) Horn clause — It can be defined as any clause containing exactly one positive literal. Since, and Then the horn clause can be written as where, H --> Horn Clause L1,L2,...,Ln --> Literals (A ⇠ B) --> can be read as 'if B then A' [Inductive Logic] and ∧ --> Conjunction (logical AND) ∨ --> Disjunction (logical OR) ¬ --> Logical NOT First Order Inductive Learner (FOIL) In machine learning, first-order inductive learner (FOIL) is a rule-based learning algorithm. It is a natural extension of SEQUENTIAL-COVERING and LEARN-ONE-RULE algorithms. It follows a Greedy approach. Inductive Learning: Inductive learning analyzing and understanding the evidence and then using it to determine the outcome. It is based on Inductive Logic. Fig 1: Inductive Logic Algorithm Involved FOIL(Target predicate, predicates, examples) • Pos ← positive examples • Neg ← negative examples • Learned rules ← {} • while Pos, do //Learn a NewRule – NewRule ← the rule that predicts target-predicate with no preconditions – NewRuleNeg ← Neg – while NewRuleNeg, do Add a new literal to specialize NewRule 1. Candidate_literals ← generate candidates for newRule based on Predicates 2. Best_literal ← argmaxL∈Candidate literalsFoil_Gain(L,NewRule) 3. add Best_literal to NewRule preconditions 4. NewRuleNeg ← subset of NewRuleNeg that satisfies NewRule preconditions – Learned rules ← Learned rules + NewRule – Pos ← Pos − {members of Pos covered by NewRule} • Return Learned rules Working of the Algorithm: In the algorithm, the inner loop is used to generate a new best rule. Let us consider an example and understand the step-by-step working of the algorithm. Fig 2 : FOIL Example Say we are tying to predict the Target-predicate- GrandDaughter(x,y). We perform the following steps: [Refer Fig 2] Step 1 - NewRule = GrandDaughter(x,y) Step 2 - 2.a - Generate the candidate_literals. (Female(x), Female(y), Father(x,y), Father(y.x), Father(x,z), Father(z,x), Father(y,z), Father(z,y)) 2.b - Generate the respective candidate literal negations. (¬Female(x), ¬Female(y), ¬Father(x,y), ¬Father(y.x), ¬Father(x,z), ¬Father(z,x), ¬Father(y,z), ¬Father(z,y)) Step 3 - FOIL might greedily select Father(x,y) as most promising, then NewRule = GrandDaughter(x,y) ← Father(y,z) [Greedy approach] Step 4 - Foil now considers all the literals from the previous step as well as: (Female(z), Father(z,w), Father(w,z), etc.) and their negations. Step 5 - Foil might select Father(z,x), and on the next step Female(y) leading to NewRule = GrandDaughter (x,y) ← Father(y,z) ∧ Father(z,x) ∧ Female(y) Step 6 - If this greedy approach covers only positive examples it terminates the search for further better results. FOIL now removes all positive examples covered by this new rule. If more are left then the outer while loop continues. FOIL: Performance Evaluation Measure The performance of a new rule is not defined by its entropy measure (like the PERFORMANCE method in Learn-One-Rule algorithm). FOIL uses a gain algorithm to determine which new specialized rule to opt. Each rule’s utility is estimated by the number of bits required to encode all the positive bindings. [Eq.1] where, L is the candidate literal to add to rule R p0 = number of positive bindings of R n0 = number of negative bindings of R p1 = number of positive binding of R + L n1 = number of negative bindings of R + L t = number of positive bindings of R also covered by R + L FOIL Algorithm is another rule-based learning algorithm that extends on the Sequential Covering + Learn-One-Rule algorithms and uses a different Performance metrics (other than entropy/information gain) to determine the best rule possible. For any doubts/queries regarding the algorithm, comment below. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Markov Decision Process k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Q-Learning in Python SARSA Reinforcement Learning
[ { "code": null, "e": 25589, "s": 25561, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25678, "s": 25589, "text": "Prerequisites: Predicates and Quantifiers, Learn-One-Rule, Sequential Covering Algorithm" }, { "code": null, "e": 25816, "s": 25678, "text": "B...
GATE | GATE-CS-2006 | Question 64 - GeeksforGeeks
14 Feb, 2018 Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest remaining time first (LRTF) scheduling algorithm. In LRTF ties are broken by giving priority to the process with the lowest process id. The average turn around time is:(A) 13 units(B) 14 units(C) 15 units(D) 16 unitsAnswer: (A)Explanation: Background Explanation:Turn around time of a process is total time between submission of the process and its completion.LRTF(Longest Remaining Time First), means the process which has remaining time largest, will run first and in case of same remaining time, lowest process with will be given priority to run. Solution: Let the processes be p0, p1 and p2. These processes will be executed in following order. Gantt chart is as follows: p2 p1 p2 p1 p2 p0 p1 p2 p0 p1 p2 0 4 5 6 7 8 9 10 11 12 13 14 First 4 sec, p2 will run, then remaining time p2=4, p1=4, p0=2. Now P1 will get chance to run for 1 sec, then remaining time. p2=4,p1=3,p0=2. Now p2 will get chance to run for 1 sec, then remaining time. p2=3,p1=3,p0=2.By doing this way, you will get above gantt chart. Scheduling table: AT=Arrival Time, BT=Burst Time, CT=Completion Time, TAT=Turn Around Time As we know, turn around time is total time between submission of the process and its completion. i.e turn around time=completion time-arrival time. i.e. TAT=CT-AT Turn around time of p0 = 12 (12-0) Turn around time of p1 = 13 (13-0) Turn around time of p2 = 14 (14-0) Average turn around time is (12+13+14)/3 = 13. Option (A) is the correct answer. See question 1 of https://www.geeksforgeeks.org/operating-systems-set-15/ This solution is contributed by Nitika BansalQuiz of this Question GATE-CS-2006 GATE-GATE-CS-2006 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-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25720, "s": 25692, "text": "\n14 Feb, 2018" }, { "code": null, "e": 26433, "s": 25720, "text": "Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest ...
java.lang.ref.WeakReference Class In Java - GeeksforGeeks
10 Dec, 2021 When we create an object in Java, an object isn’t weak by default. To create a Weak Reference Object, we must explicitly specify this to the JVM. Why Weak Reference Objects are used: Unlike C/C++, Java supports Dynamic Garbage Collection. This is performed when the JVM runs the Garbage Collector. In order to not waste space, the garbage collector deletes all unreachable objects. However, in order to mark an object for garbage collection, we can create a weak reference object. Java // Java Program to show the usage of// java.lang.ref.WeakReference Classimport java.lang.ref.WeakReference;class GFG { public static void main(String[] args) { // creating a strong object of MyClass MyClass obj = new MyClass(); // creating a weak reference of type MyClass WeakReference<MyClass> wobj = new WeakReference<>(obj); System.out.println( "-> Calling Display Function using strong object:"); obj.Display(); System.out.println("-> Object set to null"); obj = null; obj = wobj.get(); System.out.println( "-> Calling Display Function after retrieving from weak Object"); obj.Display(); }}class MyClass { void Display() { System.out.println("Display Function invoked ..."); }} -> Calling Display Function using strong object: Display Function invoked ... -> Object set to null -> Calling Display Function after retrieving from weak Object Display Function invoked ... -> Calling Display Function using strong object: Display Function invoked ... -> Object set to null -> Calling Display Function after retrieving from weak Object Display Function invoked ... Constructors in the WeakReference Class: Methods inherited from Reference Class Implementation of Methods : Java // Java Program to show the usage of// java.lang.ref.WeakReference Classimport java.lang.ref.WeakReference;class GFG { public static void main(String[] args) { X obj = new X(); WeakReference<X> weakobj = new WeakReference<X>(obj); System.out.println( "-> Retrieving object from weak reference using get ()"); weakobj.get().show(); System.out.println( "-> Is it possible to queue object using enqueue ()"); System.out.println(weakobj.enqueue()); System.out.println( "-> Checking if reference is queued using isEnqueued ()"); System.out.println(weakobj.isEnqueued()); }}class X { void show() { System.out.println("show () from X invoked.."); }} -> Retrieving object from weak reference using get () show () from X invoked.. -> Is it possible to queue object using enqueue () false -> Checking if reference is queued using isEnqueued () false ruhelaa48 anikakapoor java-lang-reflect-package Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n10 Dec, 2021" }, { "code": null, "e": 23704, "s": 23557, "text": "When we create an object in Java, an object isn’t weak by default. To create a Weak Reference Object, we must explicitly specify this to the JVM. " }, { "c...
How to search for items in a dropdown menu with CSS and JavaScript?
To search for items in a dropdown menu with CSS and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .dropbtn { background-color: rgb(76, 78, 175); color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #4f3e8e; } .searchField { box-sizing: border-box; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; } .searchField:focus {outline: 3px solid #ddd;} .dropdown { position: relative; display: inline-block; } .dropdownList { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; overflow: auto; border: 1px solid #ddd; z-index: 1; } .dropdownList a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #ddd;} .show {display: block;} </style> </head> <body> <h1>Search/filterText Dropdown Example</h1> <div class="dropdown"> <button class="dropbtn" onclick="showDropList()">Dropdown</button> <div id="myDropdown" class="dropdownList"> <input type="text" placeholder="Search.." class="searchField"> <a href="#">Cow</a> <a href="#">Cat</a> <a href="#">Dog</a> <a href="#">Giraffe</a> <a href="#">Lion</a> <a href="#">Leopard</a> <a href="#">Cheetah</a> </div> </div> <script> function showDropList(){ let dropDiv = document.querySelector('.dropdownList'); if(dropDiv.style.display==="block"){ dropDiv.style.display = ""; } else { dropDiv.style.display = "block"; } } document.querySelector('.searchField').addEventListener('keyup',filterDropdown); function filterDropdown() { var inputSearch, filterText, ul, li, links, i,div; inputSearch = document.querySelector(".searchField"); filterText = inputSearch.value.toUpperCase(); div = document.getElementById("myDropdown"); links = div.getElementsByTagName("a"); for (i = 0; i < links.length; i++) { txtValue = links[i].textContent || links[i].innerText; if (txtValue.toUpperCase().indexOf(filterText) > -1) { links[i].style.display = ""; } else { links[i].style.display = "none"; } } } </script> </body> </html> The above code will produce the following output − On clicking the Dropdown button and entering text in search field −
[ { "code": null, "e": 1151, "s": 1062, "text": "To search for items in a dropdown menu with CSS and JavaScript, the code is as follows −" }, { "code": null, "e": 1162, "s": 1151, "text": " Live Demo" }, { "code": null, "e": 3580, "s": 1162, "text": "<!DOCTYPE h...
How can I put a Java arrays inside an array?
Live Demo import java.util.Arrays; public class ArrayWithinAnArray{ public static void main(String args[]) { int[] myArray1 = {23, 56, 78, 91}; int[] myArray2 = {123, 156, 178, 191}; int[] myArray3 = {223, 256, 278, 291}; int[] myArray4 = {323, 356, 378, 391}; int [][] arrayOfArrays = {myArray1, myArray2, myArray3, myArray4}; System.out.println(Arrays.deepToString(arrayOfArrays)); } } [[23, 56, 78, 91], [123, 156, 178, 191], [223, 256, 278, 291], [323, 356, 378, 391]]
[ { "code": null, "e": 1072, "s": 1062, "text": "Live Demo" }, { "code": null, "e": 1493, "s": 1072, "text": "import java.util.Arrays;\n\npublic class ArrayWithinAnArray{\n public static void main(String args[]) {\n int[] myArray1 = {23, 56, 78, 91};\n int[] myArray2 = ...
Node.js sort() function - GeeksforGeeks
14 Oct, 2021 sort() is an array function from Node.js that is used to sort a given array. Syntax: array_name.sort() Parameter: This function does not takes any parameter. Return type: The function returns the sorted array. The program below demonstrates the working of the function: Program 1: function sortDemo(){ arr.sort() console.log(arr);}var arr=[ 3, 1, 8, 5, 2, 1];sortDemo(); Output: [ 1, 1, 2, 3, 5, 8 ] Program 2: function sortDemo(){ arr.sort() console.log(arr);}var arr=[ -3, 1, 10, 12, 1];sortDemo(); Output: [ -3, 1, 1, 10, 12 ] NodeJS-function Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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? Express.js res.sendFile() Function Express.js res.redirect() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24155, "s": 24127, "text": "\n14 Oct, 2021" }, { "code": null, "e": 24232, "s": 24155, "text": "sort() is an array function from Node.js that is used to sort a given array." }, { "code": null, "e": 24240, "s": 24232, "text": "Syntax:" },...
Spring MVC Form Validation Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here I am going show a simple Spring MVC Form Validation Example. Technologies : Spring Framework 3.1.1.RELEASE Hibernate Validator 4.2.0.Final Jstl 1.2 Java 8 Here we are going to validate registration form with different fields like firstName, lastName, age, email by using simple spring validation framework. Project Structure : Dependencies: pom.xml <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> RegistrationBean.java package com.spring.controller; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; public class RegistrationBean { @NotNull @Size(min = 1, message = "You can't leave this empty.") private String firstName; @NotNull @Size(min = 1, message = "You can't leave this empty.") private String lastName; @NotNull(message = "You can't leave this empty.") @Min(value = 13, message = "You must be greater than or equal to 13") @Max(value = 19, message = "You must be less than or equal to 19") private Integer age; @Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email") private String email; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } @NotNull: It won’t allow the null values. @Min(13): Won’t allow if the age is a min of 13 @Max(19): Won’t allow if the age is a max of 19 @Pattern: Applied given regex pattern on the specified field (our case it is email) Registration Form : register.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Spring MVC Form Validation</title> <style> .error { color: red } </style> </head> <body> <form:form action="processForm" modelAttribute="registration"> <div align="center"> <h2>Register Here</h2> <table> <tr> <td>First name</td> <td> <form:input type="text" path="firstName" /> </td> <td> <form:errors path="firstName" cssClass="error" /> </td> </tr> <tr> <td>Last name (*)</td> <td> <form:input type="text" path="lastName" /> </td> <td> <form:errors path="lastName" cssClass="error" /> </td> </tr> <tr> <td>Age </td> <td> <form:input type="text" path="age" /> </td> <td> <form:errors path="age" cssClass="error" /> </td> </tr> <tr> <td>Email </td> <td> <form:input type="text" path="email" /> </td> <td> <form:errors path="email" cssClass="error" /> </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" /></td> </tr> </table> </div> </form:form> </body> </html> Registration Controller: RegistrationController.java package com.spring.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class RegistrationController { @RequestMapping(value = "/register", method = RequestMethod.GET) public String showForm(Model model) { model.addAttribute("registration", new RegistrationBean()); return "register"; } @RequestMapping(value = "/processForm", method = RequestMethod.POST) public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "register"; } else { return "success"; } } } properties file : typeMismatch.registration.age=Invalid Number Success page: success.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Registration Confirmation</title> </head> <body> Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us. </body> </html> Run the application : http://localhost:8080/Spring-MVC-Form-Validation/register Invalid Form Fields : Leaving all form fields empty. Invalid Age : Using @Max and @Min validations on age attribute. Invalid Age Format : Giving invalid age (Not a number) validation Success Form : Success Page : Happy Learning 🙂 Spring-MVC-Form-Validation File size: 29 KB Downloads: 997 Spring Form Custom Validation Example Spring Boot Validation Login Form Example Spring Web MVC Framework Flow Spring MVC Tiles Example (Apache Tiles) Spring Boot Security MySQL Database Integration Example Python Selenium Automate the Login Form @Qualifier annotation example in Spring PHP Form Handling Example Spring Boot How to change the Tomcat to Jetty Server Spring Java Configuration Example Simple Spring Boot Example BeanFactory Example in Spring Spring Collection Map Dependency Example Spring Bean Autowire By Constructor Example Spring MVC Login Form Example Tutorials Spring Form Custom Validation Example Spring Boot Validation Login Form Example Spring Web MVC Framework Flow Spring MVC Tiles Example (Apache Tiles) Spring Boot Security MySQL Database Integration Example Python Selenium Automate the Login Form @Qualifier annotation example in Spring PHP Form Handling Example Spring Boot How to change the Tomcat to Jetty Server Spring Java Configuration Example Simple Spring Boot Example BeanFactory Example in Spring Spring Collection Map Dependency Example Spring Bean Autowire By Constructor Example Spring MVC Login Form Example Tutorials Ravinath March 16, 2019 at 12:49 pm - Reply Can I have use register.jsp to register.html? If yes! Please suggest to me. Ravi March 16, 2019 at 6:14 pm - Reply Can I create register.html instead of register.jsp file? Please Suggest me. If Yes! please give me an example. Ravinath March 16, 2019 at 12:49 pm - Reply Can I have use register.jsp to register.html? If yes! Please suggest to me. Can I have use register.jsp to register.html? If yes! Please suggest to me. Ravi March 16, 2019 at 6:14 pm - Reply Can I create register.html instead of register.jsp file? Please Suggest me. If Yes! please give me an example. Can I create register.html instead of register.jsp file? Please Suggest me. If Yes! please give me an example.
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, ...
JSF - h:outputText
The h:outputText tag renders an HTML text. <h:outputText value = "Hello World!" /> Hello World! Identifier for a component Reference to the component that can be used in a backing bean A boolean; false suppresses rendering Cascading stylesheet (CSS) class name A component’s value, typically a value binding Converter class name Inline style information A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value Let us create a test JSF application to test the above tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> <h2>h:outputText example</h2> <hr /> <h:form> <h3>Text</h3> <h:outputText value = "Hello World"/> </h:form> </body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 1995, "s": 1952, "text": "The h:outputText tag renders an HTML text." }, { "code": null, "e": 2035, "s": 1995, "text": "<h:outputText value = \"Hello World!\" />" }, { "code": null, "e": 2050, "s": 2035, "text": "Hello World! \n" }, { ...
Animate Movements of View using SpringAnimation in Android - GeeksforGeeks
19 Nov, 2021 In Android, we can add animations to an object’s movement. Instead of just updating the position of an object from one point to another, we can add some cool animations for those movements. Android provides a lot of ways that allow you to change the position of a view object on the screen with animations. But, here we are going to have a look at SpringAnimation. Spring Animation is a part of Android Physics-Based animation API. Android Spring Animation allows you to animate the movements of a view like a Spring. The animations are based on the properties like dampness, stiffness, bouncy. Once the SpringAnimation is started, on each frame the spring force will update the animation’s value and velocity. The animation will continue to run until the spring force reaches equilibrium. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. It’s really easy to create a simple spring animation. Here are the steps: Add the Support libraryCreate an instance of the SpringAnimationSet the motion behavior parametersStart the animation Add the Support library Create an instance of the SpringAnimation Set the motion behavior parameters Start the animation We can create a spring animation for an object using SpringAnimation class. First, we want to create an instance of the SpringAnimation class and provide an object(the target object for animation), an object’s property that we want to animate, and a final position for the animation to rest at. View object = findViewById(R.id.image); final SpringAnimation animation = new SpringAnimation(object, DynamicAnimation. TRANSLATION_Y, 0f); These properties control where the view is located as a delta from its left coordinate, top coordinate and elevation, which are set by its layout container. TRANSLATION_X – Left Coordinate TRANSLATION_Y – Top Coordinate TRANSLATION_Z – Depth of the view relative to its elevation. Damping ratio: It describes a gradual reduction in a spring oscillation. There are four damping ratio constants are available in the system : DAMPING_RATIO_HIGH_BOUNCY DAMPING_RATIO_MEDIUM_BOUNCY DAMPING_RATIO_LOW_BOUNCY DAMPING_RATIO_NO_BOUNCY Stiffness: It describes the strength of the spring. There are four damping ratio constants are available in the system : STIFFNESS_HIGH STIFFNESS_MEDIUM STIFFNESS_LOW STIFFNESS_VERY_LOW High Damping and low stiffness give more oscillation/bounce. To add the stiffness and damping ratio to the spring, perform the following steps Call the getString() method to retrieve the spring to add the properties.Call setDampingRatio() / setStiffness() method and pass the value that you want to add to the spring. Call the getString() method to retrieve the spring to add the properties. Call setDampingRatio() / setStiffness() method and pass the value that you want to add to the spring. To start the animation we call either start() or animateToFinalPosition(float Finalposition). Besides, updateListener and removeListener are the respective listeners for listening to update and removing the listener when it’s no longer needed. animateToFinalPosition() method performs two tasks: Sets the final position of the spring. Start the animation, if it has not started. The final position must be defined before starting the animation. Let’s see a simple example of adding SpringAnimation to an ImageView. We are going to implement this project using the Java Programming language. Step 1: Create a new project First, we want to create a new project. To create a new project in Android Studio please refer to How to Create/Start a new project in Android Studio. Step 2: To add the support library In order to use the physics-based support library, we want to add the support library to our project. 2.1. Open build.gradle file for our app module. build.gradle file (app module) 2.2. Add the support library to the dependencies dependencies { def dynamicanimation_version = '1.0.0' implementation "androidx.dynamicanimation:dynamicanimation:$dynamicanimation_version" } Step 3: Add an Image to the drawable folder To add an image to the drawable folder please refer to How to Add Image to Drawable Folder in Android Studio. You can simply add an image to the drawable folder by just copying and pasting the image in the drawable folder Navigation: app > res >drawable . Step 4: Working with activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" tools:context=".MainActivity"> <!-- Adding an ImageView for the animation --> <ImageView android:id="@+id/imageView" android:layout_width="343dp" android:layout_height="241dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0" app:srcCompat="@drawable/ic_launcher_foreground" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Add animation to the ImageView and start the animation when the image is clicked. Java import androidx.appcompat.app.AppCompatActivity;import androidx.dynamicanimation.animation.DynamicAnimation;import androidx.dynamicanimation.animation.SpringAnimation;import androidx.dynamicanimation.animation.SpringForce; import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Creating a view for the imageView final View view =findViewById(R.id.imageView); // Setting up a spring animation to animate the view final SpringAnimation animation = new SpringAnimation(view, DynamicAnimation.TRANSLATION_Y,0f); // Setting the damping ratio to create a high bouncing effect animation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_HIGH_BOUNCY); // Setting the spring with a very low stiffness animation.getSpring().setStiffness(SpringForce.STIFFNESS_VERY_LOW); // Registering the AnimationEnd listener // This will indicate the End of the animation animation.addEndListener(new DynamicAnimation.OnAnimationEndListener() { @Override public void onAnimationEnd(DynamicAnimation animation1, boolean canceled, float value, float velocity) { // set the image to the beginning of the Y axis view.setY(50f); // Again starting the animation animation.animateToFinalPosition(500f); } }); // setting a OnClickListener to the view // Starts the animation when the image is clicked view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // starts the animation animation.animateToFinalPosition(500f); } }); }} Output: Here is the output of our project. Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24725, "s": 24697, "text": "\n19 Nov, 2021" }, { "code": null, "e": 25515, "s": 24725, "text": "In Android, we can add animations to an object’s movement. Instead of just updating the position of an object from one point to another, we can add some cool anima...
JavaScript Regex to remove leading zeroes from numbers?
To remove leading zeros, use Regex in replace() method as in the below syntax − yourStringValue.replace(/\D|^0+/g, "")) Let’s say the following are our variables with number values − var theValue1="5001000"; var theValue2="100000005"; var theValue3="05000001"; var theValue4="00000000006456"; var theValue1="5001000"; var theValue2="100000005"; var theValue3="05000001"; var theValue4="00000000006456"; console.log(theValue1.replace(/\D|^0+/g, "")); console.log(theValue2.replace(/\D|^0+/g, "")); console.log(theValue3.replace(/\D|^0+/g, "")); console.log(theValue4.replace(/\D|^0+/g, "")); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo101.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo101.js 5001000 100000005 5000001 6456
[ { "code": null, "e": 1142, "s": 1062, "text": "To remove leading zeros, use Regex in replace() method as in the below syntax −" }, { "code": null, "e": 1182, "s": 1142, "text": "yourStringValue.replace(/\\D|^0+/g, \"\"))" }, { "code": null, "e": 1245, "s": 1182, ...
How to Download an Image Using Python | by Chaitanya Baweja | Towards Data Science
Recently, I was working with a remote system and needed to download some images that my code will eventually process. I could have used curl or wget on my terminal for downloading files. But, I wanted the entire process to be automated for the end-user. This led me to the question: How can I download an Image using Python? In this tutorial, I will cover several modules that can be used for downloading files in Python(specifically images). The modules covered are: requests, wget, and urllib. Disclaimer: Do not download or use any image that violates its copyright terms. Code used in this tutorial was tested on an Ubuntu system with Python 3.6.9 installed. I would highly recommend setting up a virtual environment with all the required libraries for testing. Here is how you can do it. $ virtualenv image_download$ source ./image_download/bin/activate$ pip3 install requests wget The image that we will use in the tutorial is located here. It is Free for Commercial Use and doesn’t require any attribution. The Image URL that we will use for downloading will be: https://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg We’re going to create a short script to download an image from a given URL. The script will download the image adjacent to the script file and optionally, preserve the original file name. Requests is a neat and user-friendly HTTP library in Python. It makes sending HTTP/1.1 requests extremely straightforward. It seems to be the most stable and recommended method for downloading any type of file using Python. Here is the entire code. Don’t Worry. Let’s break it down line-by-line. We will start by importing the necessary modules and will also set the Image URL. import requests # to get image from the webimport shutil # to save it locallyimage_url = "https://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg" We use slice notation to separate the filename from the image link. We split the Image URL using forward-slash( /) and then use [-1] to slice the last segment. filename = image_url.split("/")[-1] The get() method from the requests module will be used to retrieve the image. r = requests.get(image_url, stream = True) Use stream = True to guarantee no interruptions. Now, we will create the file locally in binary-write mode and use the copyfileobj() method to write our image to the file. # Set decode_content value to True, otherwise the downloaded image file's size will be zero.r.raw.decode_content = True# Open a local file with wb ( write binary ) permission.with open(filename,'wb') as f: shutil.copyfileobj(r.raw, f) We can also add certain conditionals to check if the image was retrieved successfully using Request’s Status Code. We can also improve further by adding progress bars while downloading large files or a large number of files. Here is a good example. Requests is the most stable and recommended method for downloading any type of file using Python. Apart from the python requests module, we can also use the python wget module for downloading. This is the python equivalent of GNU wget. It’s quite straightforward to use. The standard Python library for accessing websites via your program is urllib. It is also used by the requests module. Through urllib, we can do a variety of things: access websites, download data, parse data, send GET and, POST requests. We can download our image using just a few lines of code: We used the urlretrieve method to copy the required web resource to a local file. It is important to note that on some systems and a lot of websites, the above code will result in an error: HTTPError: HTTP Error 403: Forbidden. This is because a lot of websites don’t appreciate random programs accessing their data. Some programs can attack the server by sending a large number of requests. This prevents the server from functioning. This is why these websites can either: Block you and you will receive HTTP Error 403.Send you different or NULL data. Block you and you will receive HTTP Error 403. Send you different or NULL data. We can overcome this by modifying user-agent, a variable sent with our request. This variable, by default, tells the website that the visitor is a python program. By modifying this variable, we can act as if the website is being accessed on a standard web browser by a normal user. You can read more about it here. Requests has become the de-facto way of downloading things in Python. Even the urllib documentation page recommends Requests for a higher-level HTTP client interface. If you want to have fewer dependencies in your program, you should go for urllib. It is a part of the standard libraries. So, there is no need to download it. Hope you found this tutorial useful. StackOverflow — Downloading Images via Urllib and RequestsRequests Librarywget libraryurllib library StackOverflow — Downloading Images via Urllib and Requests
[ { "code": null, "e": 290, "s": 172, "text": "Recently, I was working with a remote system and needed to download some images that my code will eventually process." }, { "code": null, "e": 426, "s": 290, "text": "I could have used curl or wget on my terminal for downloading files....
8085 program to subtract two 16-bit numbers with or without borrow - GeeksforGeeks
14 Aug, 2018 Problem – Write an assembly language program in 8085 microprocessor to subtract two 16 bit numbers. Assumption – Starting address of program: 2000 Input memory location: 2050, 2051, 2052, 2053 Output memory location: 2054, 2055 Example – INPUT: (2050H) = 19H (2051H) = 6AH (2052H) = 15H (2053H) = 5CH OUTPUT: (2054H) = 04H (2055H) = OEH RESULT:Hence we have subtracted two 16 bit numbers. Algorithm – Get the LSB in L register and MSB in H register of 16 Bit number.Exchange the content of HL register with DE register.Again Get the LSB in L register and MSB in H register of 16 Bit number.Subtract the content of L register from the content of E register.Subtract the content of H register from the content of D register and borrow from previous step.Store the result in memory location. Get the LSB in L register and MSB in H register of 16 Bit number. Exchange the content of HL register with DE register. Again Get the LSB in L register and MSB in H register of 16 Bit number. Subtract the content of L register from the content of E register. Subtract the content of H register from the content of D register and borrow from previous step. Store the result in memory location. Program – Explanation – LHLD 2050: load HL pair with address 2050.XCHG: exchange the content of HL pair with DE.LHLD 2052: load HL pair with address 2050.MOV A, E: move the content of register E to A.SUB L: subtract the content of A with the content of register L.STA 2054: store the result from accumulator to memory address 2054.MOV A, D: move the content of register D to A.SBB H: subtract the content of A with the content of register H with borrow.STA 2055: store the result from accumulator to memory address 2055.HLT: stops executing the program and halts any further execution. LHLD 2050: load HL pair with address 2050. XCHG: exchange the content of HL pair with DE. LHLD 2052: load HL pair with address 2050. MOV A, E: move the content of register E to A. SUB L: subtract the content of A with the content of register L. STA 2054: store the result from accumulator to memory address 2054. MOV A, D: move the content of register D to A. SBB H: subtract the content of A with the content of register H with borrow. STA 2055: store the result from accumulator to memory address 2055. HLT: stops executing the program and halts any further execution. microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8085 microprocessor Direct Access Media (DMA) Controller in Computer Architecture Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Pin diagram of 8086 microprocessor I2C Communication Protocol 8085 program to add two 16 bit numbers General purpose registers in 8086 microprocessor 8255 microprocessor operating modes Difference between RISC and CISC processor | Set 2 Computer Organization | Different Instruction Cycles
[ { "code": null, "e": 24413, "s": 24385, "text": "\n14 Aug, 2018" }, { "code": null, "e": 24513, "s": 24413, "text": "Problem – Write an assembly language program in 8085 microprocessor to subtract two 16 bit numbers." }, { "code": null, "e": 24526, "s": 24513, ...
Annotating points from a Pandas Dataframe in Matplotlib plot
To annotate points from a Pandas dataframe in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a two-dimensional, size-mutable, potentially heterogeneous tabular data, with x, y and textc columns. Make a two-dimensional, size-mutable, potentially heterogeneous tabular data, with x, y and textc columns. Plot the columns x and y data points, using plot() method. Plot the columns x and y data points, using plot() method. Concatenate Pandas objects along a particular axis with optional set logic along the other axes. Concatenate Pandas objects along a particular axis with optional set logic along the other axes. Iterate the Pandas object. Iterate the Pandas object. Place text for each plotted points using text() method. Place text for each plotted points using text() method. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict(x=[2, 4, 1, 5, 2], y=[2, 1, 3, 5, 7], text=['First', 'Second', 'Third', 'Fourth', 'Fifth'])) ax = df.set_index('x')['y'].plot(style='*', color='red', ms=20) a = pd.concat({'x': df.x, 'y': df.y, 'text': df.text}, axis=1) for i, point in a.iterrows(): ax.text(point['x']+0.125, point['y'], str(point['text'])) plt.show()
[ { "code": null, "e": 1154, "s": 1062, "text": "To annotate points from a Pandas dataframe in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1230, "s": 1154, "text": "Set the figure size and adjust the padding between and around the subplots." }, { ...
Learn Enough Docker to be Useful. Part 3: A Dozen Dandy Dockerfile... | by Jeff Hale | Towards Data Science
This article is all about Dockerfiles. It’s the third installment in a six-part series on Docker. If you haven’t read Part 1, read it first and see Docker container concepts in a whole new light. 💡 Part 2 is a quick run-through of the Docker ecosystem. In future articles, I’ll look at slimming down Docker images, Docker CLI commands, and using data with Docker. Let’s jump into the dozen Dockerfile instructions to know! Recall that a Docker container is a Docker image brought to life. It’s a self-contained, minimal operating system with application code. The Docker image is created at build time and the Docker container is created at run time. The Dockerfile is at the heart of Docker. The Dockerfile tells Docker how to build the image that will be used to make containers. Each Docker image contains a file named Dockerfile with no extension. The Dockerfile is assumed to be in the current working directory when docker build is called to create an image. A different location can be specified with the file flag (-f). Recall that a container is built from a series of layers. Each layer is read only, except the final container layer that sits on top of the others. The Dockerfile tells Docker which layers to add and in which order to add them. Each layer is really just a file with the changes since the previous layer. In Unix, pretty much everything is a file. The base image provides the initial layer(s). A base image is also called a parent image. When an image is pulled from a remote repository to a local machine only layers that are not already on the local machine are downloaded. Docker is all about saving space and time by reusing existing layers. A Dockerfile instruction is a capitalized word at the start of a line followed by its arguments. Each line in a Dockerfile can contain an instruction. Instructions are processed from top to bottom when an image is built. Instructions look like this: FROM ubuntu:18.04COPY . /app Only the instructions FROM, RUN, COPY, and ADD create layers in the final image. Other instructions configure things, add metadata, or tell Docker to do something at run time, such as expose a port or run a command. In this article, I’m assuming you are using a Unix-based Docker image. You can also used Windows-based images, but that’s a slower, less-pleasant, less-common process. So use Unix if you can. Let’s do a quick once-over of the dozen Dockerfile instructions we’ll explore. FROM — specifies the base (parent) image.LABEL —provides metadata. Good place to include maintainer info.ENV — sets a persistent environment variable.RUN —runs a command and creates an image layer. Used to install packages into containers.COPY — copies files and directories to the container.ADD — copies files and directories to the container. Can upack local .tar files.CMD — provides a command and arguments for an executing container. Parameters can be overridden. There can be only one CMD.WORKDIR — sets the working directory for the instructions that follow.ARG — defines a variable to pass to Docker at build-time.ENTRYPOINT — provides command and arguments for an executing container. Arguments persist. EXPOSE — exposes a port.VOLUME — creates a directory mount point to access and store persistent data. Let’s get to it! A Dockerfile can be as simple as this single line: FROM ubuntu:18.04 A Dockerfile must start with a FROM instruction or an ARG instruction followed by a FROM instruction. The FROM keyword tells Docker to use a base image that matches the provided repository and tag. A base image is also called a parent image. In this example, ubuntu is the image repository. Ubuntu is the name of an official Docker repository that provides a basic version of the popular Ubuntu version of the Linux operating system. Notice that this Dockerfile includes a tag for the base image: 18.04 . This tag tells Docker which version of the image in the ubuntu repository to pull. If no tag is included, then Docker assumes the latest tag, by default. To make your intent clear, it’s good practice to specify a base image tag. When the Dockerfile above is used to build an image locally for the first time, Docker downloads the layers specified in the ubuntu image. The layers can be thought of as stacked upon each other. Each layer is a file with the set of differences from the layer before it. When you create a container, you add a writable layer on top of the read-only layers. Docker uses a copy-on-write strategy for efficiency. If a layer exists at a previous level within an image, and another layer needs read access to it, Docker uses the existing file. Nothing needs to be downloaded. When an image is running, if a layer needs modified by a container, then that file is copied into the top, writeable layer. Check out the Docker docs here to learn more about copy-on-write. Although our one-line image is concise, it’s also slow, provides little information, and does nothing at container run time. Let’s look at a longer Dockerfile that builds a much smaller size image and executes a script at container run time. FROM python:3.7.2-alpine3.8LABEL maintainer="jeffmshale@gmail.com"ENV ADMIN="jeff"RUN apk update && apk upgrade && apk add bashCOPY . ./appADD https://raw.githubusercontent.com/discdiver/pachy-vid/master/sample_vids/vid1.mp4 \/my_app_directoryRUN ["mkdir", "/a_directory"]CMD ["python", "./my_script.py"] Whoa, what’s going on here? Let’s step through it and demystify. The base image is an official Python image with the tag 3.7.2-alpine3.8. As you can see from its source code, the image includes Linux, Python and not much else. Alpine images are popular because they are small, fast, and secure. However, Alpine images don’t come with many operating system niceties. You must install such packages yourself, should you need them. The next instruction is LABEL. LABEL adds metadata to the image. In this case, it provides the image maintainer’s contact info. Labels don’t slow down builds or take up space and they do provide useful information about the Docker image, so definitely use them. More about LABEL metadata can be found here. ENV sets a persistent environment variable that is available at container run time. In the example above, you could use the ADMIN variable when your Docker container is created. ENV is nice for setting constants. If you use a constant several places in your Dockerfile and want to change its value at a later time, you can do so in one location. With Dockerfiles there are often multiple ways to accomplish the same thing. The best method for your case is a matter of balancing Docker conventions, transparency, and speed. For example, RUN, CMD, and ENTRYPOINT serve different purposes, and can all be used to execute commands. RUN creates a layer at build-time. Docker commits the state of the image after each RUN. RUN is often used to install packages into an image. In the example above, RUN apk update && apk upgrade tells Docker to update the packages from the base image. && apk add bash tells Docker to install bash into the image. apk stands for Alpine Linux package manager. If you’re using a Linux base image in a flavor other than Alpine, then you’d install packages with RUN apt-get instead of apk. apt stand for advanced package tool. I’ll discuss other ways to install packages in a later example. RUN — and its cousins, CMD and ENTRYPOINT — can be used in exec form or shell form. Exec form uses JSON array syntax like so: RUN ["my_executable", "my_first_param1", "my_second_param2"]. In the example above, we used shell form in the format RUN apk update && apk upgrade && apk add bash. Later in our Dockerfile we used the preferred exec form with RUN ["mkdir", "/a_directory"] to create a directory. Don’t forget to use double quotes for strings with JSON syntax for exec form! The COPY . ./app instruction tells Docker to take the files and folders in your local build context and add them to the Docker image’s current working directory. Copy will create the target directory if it doesn’t exist. ADD does the same thing as COPY, but has two more use cases. ADD can be used to move files from a remote URL to a container and ADD can extract local TAR files. I used ADD in the example above to copy a file from a remote url into the container’s my_app_directory. The Docker docs don’t recommend using remote urls in this manner because you can’t delete the files. Extra files increase the final image size. The Docker docs also suggest using COPY instead of ADD whenever possible for improved clarity. It’s too bad that Docker doesn’t combine ADD and COPY into a single command to reduce the number of Dockerfile instructions to keep straight 😃. Note that the ADD instruction contains the \ line continuation character. Use it to improve readability by breaking up a long instruction over several lines. CMD provides Docker a command to run when a container is started. It does not commit the result of the command to the image at build time. In the example above, CMD will have the Docker container run the my_script.py file at run time. A few other things to know about CMD: Only one CMD instruction per Dockerfile. Otherwise all but the final one are ignored. CMD can include an executable. If CMD is present without an executable, then an ENTRYPOINT instruction must exist. In that case, both CMD and ENTRYPOINT instructions should be in JSON format. Command line arguments to docker run override arguments provided to CMD in the Dockerfile. Let’s introduce a few more instructions in another example Dockerfile. FROM python:3.7.2-alpine3.8LABEL maintainer="jeffmshale@gmail.com"# Install dependenciesRUN apk add --update git# Set current working directoryWORKDIR /usr/src/my_app_directory# Copy code from your local context to the image working directoryCOPY . .# Set default value for a variableARG my_var=my_default_value# Set code to run at container run timeENTRYPOINT ["python", "./app/my_script.py", "my_var"]# Expose our port to the worldEXPOSE 8000# Create a volume for data storageVOLUME /my_volume Note that you can use comments in Dockerfiles. Comments start with #. Package installation is a primary job of Dockerfiles. As touched on earlier, there are several ways to install packages with RUN. You can install a package in an Alpine Docker image with apk. apk is like apt-get in regular Linux builds. For example, packages in a Dockerfile with a base Ubuntu image can be updated and installed like this: RUN apt-get update && apt-get install my_package. In addition to apk and apt-get, Python packages can be installed through pip, wheel, and conda. Other languages can use various installers. The underlying layers need to provide the install layer with the the relevant package manger. If you’re having an issue with package installation, make sure the package managers are installed before you try to use them. 😃 You can use RUN with pip and list the packages you want installed directly in your Dockerfile. If you do this concatenate your package installs into a single instruction and break it up with line continuation characters (\). This method provides clarity and fewer layers than multiple RUN instructions. Alternatively, you can list your package requirements in a file and RUN a package manager on that file. Folks usually name the file requirements.txt. I’ll share a recommended pattern to take advantage of build time caching with requirements.txt in the next article. WORKDIR changes the working directory in the container for the COPY, ADD, RUN, CMD, and ENTRYPOINT instructions that follow it. A few notes: It’s preferable to set an absolute path with WORKDIR rather than navigate through the file system with cd commands in the Dockerfile. WORKDIR creates the directory automatically if it doesn’t exist. You can use multiple WORKDIR instructions. If relative paths are provided, then each WORKDIR instruction changes the current working directory. ARG defines a variable to pass from the command line to the image at build-time. A default value can be supplied for ARG in the Dockerfile, as it is in the example: ARG my_var=my_default_value. Unlike ENV variables, ARG variables are not available to running containers. However, you can use ARG values to set a default value for an ENV variable from the command line when you build the image. Then, the ENV variable persists through container run time. Learn more about this technique here. The ENTRYPOINT instruction also allows you provide a default command and arguments when a container starts. It looks similar to CMD, but ENTRYPOINT parameters are not overwritten if a container is run with command line parameters. Instead, command line arguments passed to docker run my_image_name are appended to the ENTRYPOINT instruction’s arguments. For example, docker run my_image bash adds the argument bash to the end of the ENTRYPOINT instruction’s existing arguments. A Dockerfile should have at least one CMD or ENTRYPOINT instruction. The Docker docs have a few suggestions for choosing between CMD and ENTRYPOINT for your initial container command: Favor ENTRYPOINT when you need to run the same command every time. Favor ENTRYPOINT when a container will be used as an executable program. Favor CMD when you need to provide extra default arguments that could be overwritten from the command line. In the example above, ENTRYPOINT ["python", "my_script.py", "my_var"] has the container run the the python script my_script.py with the argument my_var when the container starts running. my_var could then be used by my_script via argparse. Note that my_var has a default value supplied by ARG earlier in the Dockerfile. So if an argument isn’t passed from the command line, then the default argument will be used. Docker recommends you generally use the exec form of ENTRYPOINT: ENTRYPOINT ["executable", "param1", "param2"]. This form is the one with JSON array syntax. EXPOSE The EXPOSE instruction shows which port is intended to be published to provide access to the running container. EXPOSE does not actually publish the port. Rather, it acts as a documentation between the person who builds the image and the person who runs the container. Use docker run with the -p flag to publish and map one or more ports at run time. The uppercase -P flag will publish all exposed ports. VOLUME specifies where your container will store and/or access persistent data. Volumes are the topic of a forthcoming article in this series, so we’ll investigate them then. Let’s review the dozen Dockerfile instructions we’ve explored. FROM — specifies the base (parent) image.LABEL —provides metadata. Good place to include maintainer info.ENV — sets a persistent environment variable.RUN —runs a command and creates an image layer. Used to install packages into containers.COPY — copies files and directories to the container.ADD — copies files and directories to the container. Can upack local .tar files.CMD — provides a command and arguments for an executing container. Parameters can be overridden. There can be only one CMD.WORKDIR — sets the working directory for the instructions that follow.ARG — defines a variable to pass to Docker at build-time.ENTRYPOINT — provides command and arguments for an executing container. Arguments persist. EXPOSE — exposes a port.VOLUME — creates a directory mount point to access and store persistent data. Now you know a dozen Dockerfile instructions to make yourself useful! Here’s a bonus bagel: a cheat sheet with all the Dockerfile instructions. The five commands we didn’t cover are USER, ONBUILD, STOPSIGNAL, SHELL, and HEALTHCHECK. Now you’ve seen their names if you come across them. 😃 Dockerfiles are perhaps the key component of Docker to master. I hope this article helped you gain confidence with them. We’ll revisit them in the next article in this series on slimming down images. Follow me to make sure you don’t miss it! If you found this article helpful, please help others find it by sharing on your favorite social media. 👍 I write about data science, cloud computing, and other tech stuff. Follow me and read more here.
[ { "code": null, "e": 536, "s": 172, "text": "This article is all about Dockerfiles. It’s the third installment in a six-part series on Docker. If you haven’t read Part 1, read it first and see Docker container concepts in a whole new light. 💡 Part 2 is a quick run-through of the Docker ecosystem. I...
What is H – Index?
18 Aug, 2020 What is H – index ? ‘H’ stands for Hirsch index as it was proposed by the J.E. Hirsch in 2005. The h-index is defined as the author-level metric that attempts to measure both the productivity and the citation impact of the publication of the scientist or the scholar. There are two parameters to be considered – Quantity – Numbers of papersQuality – Number of citations Quantity – Numbers of papers Quality – Number of citations Basically, H-index is the largest number such that a number of publications have at least the same number of citations. As a useful index to characterize the scientific output of a researcher. Calculating the H-index – For example, consider a Researcher has published total 10 papers. H-index is always <= total numbers of papers published For convenience let us arrange the number of citations in decreasing order. H-index can not be 10, because there must be at least 10 research papers which have 10 or more than 10 citations. Similarly, H-index can not be 9, H-index can not be 8, H-index is 7 as there are 7 research papers having 7 or more than 7 citations. Example : Input : Citations = [7, 6, 5, 4, 3] Output : 4 Explanation : There are 5 papers in total. Since the researcher has 4 papers with at least 4 citations each and the remaining one paper has less than 4 citations. So H-index is 4. Approach for finding the H – index : Sort the citation array in ascending order or descending order.Iterate from the lowest paper to the highest paper.The remaining papers (result) is the count of papers that satisfy the condition for H-index. Sort the citation array in ascending order or descending order. Iterate from the lowest paper to the highest paper. The remaining papers (result) is the count of papers that satisfy the condition for H-index. # calculating H-Indexdef H_index(citations): # sorting in ascending order citations.sort() # iterating over the list for i, cited in enumerate(citations): # finding current result result = len(citations) - i # if result is less than or equal # to cited then return result if result <= cited: return result return 0 # creating the citationscitation = [50, 40, 33, 23, 12, 11, 8, 5, 1, 0] # calling the functionprint(H_index(citation)) Output 7 Time Complexity : O(nlogn + n)Space Complexity : O(1) Limitations of H – Index : Different fields of researchers can have different citation behavior.We can not compare two researchers having different field and huge gap of research experience. Experienced researcher will have high H-index as compare to less experienced researcher.H-index value depends on the database you are using it may vary for the different platform. Different fields of researchers can have different citation behavior. We can not compare two researchers having different field and huge gap of research experience. Experienced researcher will have high H-index as compare to less experienced researcher. H-index value depends on the database you are using it may vary for the different platform. Data Analytics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Aug, 2020" }, { "code": null, "e": 322, "s": 54, "text": "What is H – index ? ‘H’ stands for Hirsch index as it was proposed by the J.E. Hirsch in 2005. The h-index is defined as the author-level metric that attempts to measure both...
Pandas – Get the elements of series that are not present in other series
11 Oct, 2020 Sometimes we have two or more series and we have to find all those elements that are present in one series but not in other. We can do this easily, using the Bitwise NOT operator along with the pandas.isin() function. Example 1: Taking two Integer Series Python3 # Importing pandas libraryimport pandas as pd # Creating 2 pandas Seriesps1 = pd.Series([2, 4, 8, 20, 10, 47, 99])ps2 = pd.Series([1, 3, 6, 4, 10, 99, 50]) print("Series1:")print(ps1)print("\nSeries2:")print(ps2) # Using Bitwise NOT operator along# with pandas.isin()print("\nItems of ps1 not present in ps2:")res = ps1[~ps1.isin(ps2)]print(res) Output: In the above example, we take 2 pandas series of int type ‘ps1‘ and ‘ps2‘ and find all those elements of ps1 that are not present in ps2. Example 2: Taking two Floating point Series Python3 # Importing pandas libraryimport pandas as pd # Creating 2 pandas Series ps1 = pd.Series([2.8, 4.5, 8.0, 2.2, 10.1, 4.7, 9.9])ps2 = pd.Series([1.4, 2.8, 4.7, 4.8, 10.1, 9.9, 50.12]) print("Series1:")print(ps1)print("\nSeries2:")print(ps2) # Using Bitwise NOT operator along # with pandas.isin()print("\nItems of ps1 not present in ps2:")res = ps1[~ps1.isin(ps2)]print(res) Output: In the above example, we take 2 pandas series of float type ‘ps1‘ and ‘ps2‘ and find all those elements of ps1 that are not present in ps2. Example 3: Taking two String Series Python3 # Importing pandas libraryimport pandas as pd # Creating 2 pandas Seriesps1 = pd.Series(['Monu', 'Sonu', 'Tonu', 'Nonu', 'Ronu', 'Bonu']) ps2 = pd.Series(['Sweetu', 'Tweetu', 'Nonu', 'Micku', 'Bonu', 'Kicku']) print("Series1:")print(ps1)print("\nSeries2:")print(ps2) # Using Bitwise NOT operator along with# pandas.isin()print("\nItems of ps1 not present in ps2:")res = ps1[~ps1.isin(ps2)]print(res) Output: In the above example, we take 2 pandas series of string type ‘ps1‘ and ‘ps2‘ and find all those elements of ps1 that are not present in ps2. Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 246, "s": 28, "text": "Sometimes we have two or more series and we have to find all those elements that are present in one series but not in other. We can do this easily, using the Bitwise NOT opera...
What is stacktrace and how to print in node.js ?
31 May, 2020 Node.js is an open-source project that can be used for server-side scripting. Node.js is a cross-platform which allows the developers to code without having to worry about the runtime environment. Node.js is widely used for building dynamic, light-weight, and scalable web applications. Node.js provides a JavaScript runtime environment that can be used for both frontend and backend development. However, applications often throw errors or exceptions that must be handled. A Stack trace is displayed automatically by the JVM to indicate that an error has occurred during the program execution. The stack trace is used to trace the active stack frames at a particular instance during the execution of a program. The stack trace is useful while debugging code as it shows the exact point that has caused an error. Errors in Node.js can be classified into four broad categories: Standard JavaScript Errors System Errors User-specified Errors Assertion Errors Node.js supports several mechanisms for propagating and handling errors that occur during program execution. All Standard JavaScript Errors are handled immediately by throwing an error which can be viewed in the stack trace. There are four methods to print the stack trace in Node.js that are: Using error.stack Property: The error.stack property describes the point in the code at which the Error was instantiated.Syntax:error.stackExample:console.log("This program demonstrates " + "stack trace in Node.js");var err = new Error().stackconsole.log(err);Output:This program demonstrates stack trace in Node.js Error at Object. (/home/cg/root/2523129/main.js:20:11) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Syntax: error.stack Example: console.log("This program demonstrates " + "stack trace in Node.js");var err = new Error().stackconsole.log(err); Output: This program demonstrates stack trace in Node.js Error at Object. (/home/cg/root/2523129/main.js:20:11) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Using Error.captureStackTrace() Method: This method creates a .stack property on obj that returns a string representing the point in the code at which Error.captureStackTrace(obj) was called. The func parameter represents a function which is optional.Syntax:Error.captureStackTrace(obj, func)Example:const obj = {};Error.captureStackTrace(obj);console.log(obj.stack); // Alternativelyfunction MyNewError() { Error.captureStackTrace(this, MyNewError);} console.log(new MyNewError().stack);Output:Error at Object. (/home/cg/root/2523129/main.js:25:13) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Syntax:Error.captureStackTrace(obj, func) Example: const obj = {};Error.captureStackTrace(obj);console.log(obj.stack); // Alternativelyfunction MyNewError() { Error.captureStackTrace(this, MyNewError);} console.log(new MyNewError().stack); Output: Error at Object. (/home/cg/root/2523129/main.js:25:13) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Using try-catch block: It is a mechanism of Error Handling and it is used when a piece of code is surrounded in a try block and throw an error to the catch block. If the error is not handled then the program terminates abruptly.Example:try { throw new Error("Error occurred"); }catch(e) { console.log(e);}Output:Error at Object. (/home/cg/root/2523129/main.js:25:13) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Example: try { throw new Error("Error occurred"); }catch(e) { console.log(e);} Output: Error at Object. (/home/cg/root/2523129/main.js:25:13) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Using trace command: The console.trace() method is used to display the trace which represents how the code ended up at a certain point.Example:console.trace("hello world");Output:Trace: hello world at Object. (/home/cg/root/2523129/main.js:28:9) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Example: console.trace("hello world"); Output: Trace: hello world at Object. (/home/cg/root/2523129/main.js:28:9) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:504:3 Node.js-Misc Picked Node.js 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": "\n31 May, 2020" }, { "code": null, "e": 502, "s": 28, "text": "Node.js is an open-source project that can be used for server-side scripting. Node.js is a cross-platform which allows the developers to code without having to worry about the...
How to set checkbox size in HTML/CSS?
30 Jul, 2021 The checkbox is an HTML element which is used to take input from the user.Method 1: The checkbox size can be set by using height and width property. The height property sets the height of checkbox and width property sets the width of the checkbox. Syntax: input./*checkbox class name*/ { width : /*desired width*/; height : /*desired height*/; } Example: <!DOCTYPE html> <html> <head> <title> Set checkbox size </title> <!-- Style to set the size of checkbox --> <style> input.largerCheckbox { width: 40px; height: 40px; } </style></head> <body> <input type="checkbox" class="defaultCheckbox" name="checkBox1" checked> <input type="checkbox" class="largerCheckbox" name="checkBox2" checked></body> </html> Output: Note: This works well for Google Chrome, Microsoft Edge and Internet Explorer. In Mozilla Firefox the clickable checkbox area is as specified but it displays a checkbox of the default size. Method 2: An alternate solution that works for Mozilla Firefox as well is by using transform property. Syntax: input./*checkbox class name*/ { transform : scale(/*desired magnification*/); } Example: <!DOCTYPE html> <html> <head> <title> Set the size of checkbox </title> <!-- Use transform scale property to set size of checkbox --> <style> input.largerCheckbox { transform : scale(10); } body { text-align:center; margin-top:100px; } </style></head> <body> <input type="checkbox" class="largerCheckbox" name="checkBox2" checked></body> </html> Output:This method has a few drawbacks. The checkbox has to be positioned carefully to keep it within the browser window or prevent it from overlapping with other elements. Also, in some browsers, the checkbox may appear pixelated for larger sizes. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc HTML-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 276, "s": 28, "text": "The checkbox is an HTML element which is used to take input from the user.Method 1: The checkbox size can be set by using height and width property. The height property sets t...
HTML | DOM Input Date min Property
07 Dec, 2021 The Input Date min property is used for setting or returning the value of the min attribute of a date field. The attribute returns a string that represents the minimum date allowed. Syntax: For returning the min property: inputdateObject.min For setting the min property: inputdateObject.min = YYYY-MM-DD Property Value: YYYY-MM-DDThh:mm:ssTZD :It is used to specify the minimum date and time allowed. YYYY: It specifies the year.MM: It specifies the month.DD: It specifies the day of the month.T: It specifies the separator if time is also entered.hh: It specifies the hour.mm: It specifies the minutes.ss: It specifies the seconds.TZD: It specifies the Time Zone Designator. YYYY: It specifies the year. MM: It specifies the month. DD: It specifies the day of the month. T: It specifies the separator if time is also entered. hh: It specifies the hour. mm: It specifies the minutes. ss: It specifies the seconds. TZD: It specifies the Time Zone Designator. Return Values: It returns a string value which represents the minimum date that has been allowed for date field. Below program illustrates the Date min property:Example 1: Getting the minimum date allowed for a date field. html <!DOCTYPE html><html> <head> <title>Input Date min Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date min Property</h2> <br> <p>The range of date accepted is between 2019-02-18 and 2019-02-20: <input type="date" id="Test_Date" min="2019-02-18" max="2019-02-20"> <p>To return the min range of the date field, double click the "Return Min" button.</p> <button ondblclick="My_Date()">Return Min</button> <p id="test"></p> <script> function My_Date() { var d = document.getElementById("Test_Date").min; document.getElementById("test").innerHTML = d; } </script> </body> </html> Output: Before: After clicking the button: Example-2: Below code sets the Input Date min property. HTML <!DOCTYPE html><html> <head> <title>Input Date min Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date min Property</h2> <br>: <input type="date" id="Test_Date" min="2019-02-18" max="2019-02-20"> <p>To set the min range of the date field, double click the "Set Min" button.</p> <button ondblclick="My_Date()">Set Min</button> <p id="test"></p> <script> function My_Date() { var d = document.getElementById("Test_Date").min = "2019-01-01"; document.getElementById("test").innerHTML = d; } </script> </body> </html> Before: After double clicking the button: Supported Web Browsers: Apple Safari Internet Explorer Firefox Google Chrome Opera ManasChhabra2 hritikbhatnagar2182 chhabradhanvi HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Dec, 2021" }, { "code": null, "e": 235, "s": 53, "text": "The Input Date min property is used for setting or returning the value of the min attribute of a date field. The attribute returns a string that represents the minimum date a...
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
23 Jun, 2022 Given an array of positive numbers, find the smallest positive integer value that cannot be represented as the sum of elements of any subset of a given set. The expected time complexity is O(nlogn). Examples: Input: arr[] = {1, 10, 3, 11, 6, 15}; Output: 2 Input: arr[] = {1, 1, 1, 1}; Output: 5 Input: arr[] = {1, 1, 3, 4}; Output: 10 Input: arr[] = {1, 2, 5, 10, 20, 40}; Output: 4 Input: arr[] = {1, 2, 3, 4, 5, 6}; Output: 22 A Simple Solution is to start from value 1 and check all values one by one if they can sum to values in the given array. This solution is very inefficient as it reduces to the subset sum problem which is a well-known NP-Complete Problem. Using a simple loop, we can solve this problem in O(N log N) time. Let the input array be arr[0..n-1]. We first sort the array in non-decreasing order. Let the smallest element that cannot be represented by elements at indexes from 0 to (i-1) be ‘res’. We initialize ‘res’ as 1 (smallest possible answer) and traverse the given array from i=0. There are the following two possibilities when we consider element at index i: We decide that ‘res’ is the final result: If arr[i] is greater than ‘res’, then we found the gap which is ‘res’ because the elements after arr[i] are also going to be greater than ‘res’.The value of ‘res’ is incremented after considering arr[i]: If arr[i] is not greater than ‘res’, the value of ‘res’ is incremented by arr[i] so ‘res’ = ‘res’+arr[i] (why? If elements from 0 to (i-1) can We decide that ‘res’ is the final result: If arr[i] is greater than ‘res’, then we found the gap which is ‘res’ because the elements after arr[i] are also going to be greater than ‘res’. The value of ‘res’ is incremented after considering arr[i]: If arr[i] is not greater than ‘res’, the value of ‘res’ is incremented by arr[i] so ‘res’ = ‘res’+arr[i] (why? If elements from 0 to (i-1) can represent 1 to ‘res-1’, then elements from 0 to i can represent from 1 to ‘res + arr[i] – 1’ by adding arr[i] to all subsets that represent 1 to ‘res-1’ which we have already determined to be represented)Following is the implementation of the above idea. C++ Java Python3 C# PHP Javascript // C++ program to find the smallest positive value that cannot be// represented as sum of subsets of a given sorted array#include<iostream>#include<vector>#include<algorithm>using namespace std; // Returns the smallest number that cannot be represented as sum// of subset of elements from set represented by sorted array arr[0..n-1]long long smallestpositive(vector<long long> arr, int n) { long long int res = 1; // Initialize result sort(arr.begin(), arr.end()); // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } // Driver program to test above functionint main() { vector<long long> arr1 = {1, 3, 4, 5}; cout << smallestpositive(arr1, arr1.size()) << endl; vector<long long> arr2 = {1, 2, 6, 10, 11, 15}; cout << smallestpositive(arr2, arr2.size()) << endl; vector<long long> arr3 = {1, 1, 1, 1}; cout << smallestpositive(arr3, arr3.size()) << endl; vector<long long> arr4 = {1, 1, 3, 4}; cout << smallestpositive(arr4, arr4.size()) << endl; return 0; } // Java program to find the smallest positive value that cannot be// represented as sum of subsets of a given sorted arrayimport java.util.Arrays; class FindSmallestInteger{ // Returns the smallest number that cannot be represented as sum // of subset of elements from set represented by sorted array arr[0..n-1] int findSmallest(int arr[], int n) { int res = 1; // Initialize result // sort the input array Arrays.sort(arr); // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n; i++) { if(arr[i] > res){ return res; } else{ res+=arr[i]; } } return res; } // Driver program to test above functions public static void main(String[] args) { FindSmallestInteger small = new FindSmallestInteger(); int arr1[] = {1, 3, 4, 5}; int n1 = arr1.length; System.out.println(small.findSmallest(arr1, n1)); int arr2[] = {1, 2, 6, 10, 11, 15}; int n2 = arr2.length; System.out.println(small.findSmallest(arr2, n2)); int arr3[] = {1, 1, 1, 1}; int n3 = arr3.length; System.out.println(small.findSmallest(arr3, n3)); int arr4[] = {1, 1, 3, 4}; int n4 = arr4.length; System.out.println(small.findSmallest(arr4, n4)); }} // This code has been contributed by Mukul Sharma (msharma04) # Python3 program to find the smallest# positive value that cannot be# represented as sum of subsets# of a given sorted array # Returns the smallest number# that cannot be represented as sum# of subset of elements from set# represented by sorted array arr[0..n-1]def findSmallest(arr, n): res = 1 #Initialize result # Traverse the array and increment # 'res' if arr[i] is smaller than # or equal to 'res'. for i in range (0, n ): if arr[i] <= res: res = res + arr[i] else: break return res # Driver program to test above functionarr1 = [1, 3, 4, 5]n1 = len(arr1)print(findSmallest(arr1, n1)) arr2= [1, 2, 6, 10, 11, 15]n2 = len(arr2)print(findSmallest(arr2, n2)) arr3= [1, 1, 1, 1]n3 = len(arr3)print(findSmallest(arr3, n3)) arr4 = [1, 1, 3, 4]n4 = len(arr4)print(findSmallest(arr4, n4)) # This code is.contributed by Smitha Dinesh Semwal // C# program to find the smallest// positive value that cannot be// represented as sum of subsets// of a given sorted arrayusing System; class GFG { // Returns the smallest number that // cannot be represented as sum // of subset of elements from set // represented by sorted array // arr[0..n-1] static int findSmallest(int []arr, int n) { // Initialize result int res = 1; // Traverse the array and // increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } // Driver code public static void Main() { int []arr1 = {1, 3, 4, 5}; int n1 = arr1.Length; Console.WriteLine(findSmallest(arr1, n1)); int []arr2 = {1, 2, 6, 10, 11, 15}; int n2 = arr2.Length; Console.WriteLine(findSmallest(arr2, n2)); int []arr3 = {1, 1, 1, 1}; int n3 = arr3.Length; Console.WriteLine(findSmallest(arr3, n3)); int []arr4 = {1, 1, 3, 4}; int n4 = arr4.Length; Console.WriteLine(findSmallest(arr4, n4)); }} // This code is contributed by Sam007 <?php// PHP program to find the smallest// positive value that cannot be// represented as sum of subsets// of a given sorted array // Returns the smallest number that// cannot be represented as sum of// subset of elements from set// represented by sorted array// arr[0..n-1]function findSmallest($arr, $n){ // Initialize result $res = 1; // Traverse the array and // increment 'res' if arr[i] is // smaller than or equal to 'res'. for($i = 0; $i < $n and $arr[$i] <= $res; $i++) $res = $res + $arr[$i]; return $res;} // Driver Code$arr1 = array(1, 3, 4, 5);$n1 = count($arr1);echo findSmallest($arr1, $n1),"\n"; $arr2 = array(1, 2, 6, 10, 11, 15);$n2 = count($arr2);echo findSmallest($arr2, $n2),"\n" ; $arr3 = array(1, 1, 1, 1);$n3 = count($arr3);echo findSmallest($arr3, $n3),"\n"; $arr4 = array(1, 1, 3, 4);$n4 = count($arr4);echo findSmallest($arr4, $n4); // This code is contributed by anuj_67.?> <script>// javascript program to find the smallest positive value that cannot be// represented as sum of subsets of a given sorted array // Returns the smallest number that cannot be represented as sum // of subset of elements from set represented by sorted array arr[0..n-1] function findSmallest(arr , n) { var res = 1; // Initialize result // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } // Driver program to test above functions var arr1 = [ 1, 3, 4, 5 ]; var n1 = arr1.length; document.write(findSmallest(arr1, n1)+"<br/>"); var arr2 = [ 1, 2, 6, 10, 11, 15 ]; var n2 = arr2.length; document.write(findSmallest(arr2, n2)+"<br/>"); var arr3 = [ 1, 1, 1, 1 ]; var n3 = arr3.length; document.write(findSmallest(arr3, n3)+"<br/>"); var arr4 = [ 1, 1, 3, 4 ]; var n4 = arr4.length; document.write(findSmallest(arr4, n4)+"<br/>"); // This code is contributed by aashish1995</script> 2 4 5 10 The Time Complexity of the above program is O(nlogn). The Space Complexity is O(1) in best case for heap sort. Sam007 vt_m aashish1995 krishan21723 nush1501 mdsheraj msharma04 technophpfij hardikkoriintern Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 251, "s": 52, "text": "Given an array of positive numbers, find the smallest positive integer value that cannot be represented as the sum of elements of any subset of a given set. The expected time...
close() method in PyQt5
26 Mar, 2020 In this article, we will see how to use close() method which belongs to the QWidget class, this method is used to close the window in PyQt5 application. In other words by close() method the window get closed without manually closing it. Syntax : self.close() Argument : It takes no argument. Code : # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sysimport time class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Close") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel("Icon is set", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet("border: 1px solid black;") # show all the widgets self.show() # waiting for 2 second time.sleep(2) # closing the window self.close() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) This will open the window and after 2 seconds it will automatically closes the window. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 265, "s": 28, "text": "In this article, we will see how to use close() method which belongs to the QWidget class, this method is used to close the window in PyQt5 application. In other words by clos...
Python | Pair the consecutive character strings in a list
26 Nov, 2019 Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or competitive programming. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + zip()Combination of above functionalities can be used to solve this problem. In this, we iterate the list using list comprehension and formation of pairs using zip(). # Python3 code to demonstrate working of# Consecutive element pairing in list# using list comprehension + zip() # initialize list test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"] # printing original list print("The original list : " + str(test_list)) # Consecutive element pairing in list# using list comprehension + zip()res = [i + j for i, j in zip(test_list, test_list[1:])] # printing resultprint("List after Consecutive concatenation is : " + str(res)) The original list : [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’]List after Consecutive concatenation is : [‘GF’, ‘FG’, ‘GI’, ‘IS’, ‘SB’, ‘BE’, ‘ES’, ‘ST’] Method #2 : Using map() + concat()The combination of these functions can also perform this task. In this traversal logic is done by map() and concat performs the task of pairing. It’s more efficient than above method. # Python3 code to demonstrate working of# Consecutive element pairing in list# using map() + concatimport operator # initialize list test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"] # printing original list print("The original list : " + str(test_list)) # Consecutive element pairing in list# using map() + concatres = list(map(operator.concat, test_list[:-1], test_list[1:])) # printing resultprint("List after Consecutive concatenation is : " + str(res)) The original list : [‘G’, ‘F’, ‘G’, ‘I’, ‘S’, ‘B’, ‘E’, ‘S’, ‘T’]List after Consecutive concatenation is : [‘GF’, ‘FG’, ‘GI’, ‘IS’, ‘SB’, ‘BE’, ‘ES’, ‘ST’] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2019" }, { "code": null, "e": 288, "s": 28, "text": "Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or comp...
PHP | filter_input() Function
14 Feb, 2019 The filter_input() is an inbuilt function in PHP which is used to get the specific external variable by name and filter it. This function is used to validate variables from insecure sources, such as user input from form. This function is very much useful to prevent some potential security threat like SQL Injection. Syntax: filter_input( $type, $variable_name, $filter, $options) Parameters: This function accepts four parameters as mentioned above and described below: $type: It is mandatory parameter and used to check the type of input. The list of filters are:INPUT_GETINPUT_POSTINPUT_COOKIEINPUT_SERVERINPUT_ENV INPUT_GET INPUT_POST INPUT_COOKIE INPUT_SERVER INPUT_ENV $variable_name: It is required parameter. It is used to hols the name of variable which is to be checked. $filter: It is an optional parameter. It holds the name or ID of the filter. If this parameter is not set then FILTER_DEFAULT is used. $options: It is an optional parameter and used to specify one or more flags/options to use. It check for possible options and flags in each filter. If filter options are accepted then flags can be provided in “flags” field of array. Return Value: It returns the value of the variable on success or False on failure. If parameter is not set then return NULL. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails. Example 1: <?php// PHP program to validate email using filter if (isset($_GET["email"])) { if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) { echo("Valid Email"); } else { echo("Invalid Email"); }} ?> Output: Valid Email Example 2: <?php // Input type:INPUT_GET input name:search // filter name:FILTER_SANITIZE_SPECIAL_CHARS$search_variable_data = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS); // Input type:INPUT_GET input name:search// filter name:FILTER_SANITIZE_ENCODED$search_url_data = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED); echo "Search for $search_variable_data.\n"; echo "<a href='?search=$search_url_data'>Search again.</a>"; ?> Output: Search for tic tac & toc. Search again. References: http://php.net/manual/en/function.filter-input.php PHP-function PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP? Download file from URL using PHP How to fetch data from localserver database and display on HTML table using PHP ? How to pass JavaScript variables to PHP ? Difference between HTTP GET and POST Methods How to Encrypt and Decrypt a PHP String ? How to declare a global variable in PHP?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2019" }, { "code": null, "e": 345, "s": 28, "text": "The filter_input() is an inbuilt function in PHP which is used to get the specific external variable by name and filter it. This function is used to validate variables from in...
Node.js | NPM (Node Package Manager)
08 Mar, 2022 NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially released in January 12, 2010. NPM manages all the packages and modules for Node.js and consists of command line client npm. It gets installed into the system with installation of Node.js. The required packages and modules in Node project are installed using NPM.A package contains all the files needed for a module and modules are the JavaScript libraries that can be included in Node project according to the requirement of the project.NPM can install all the dependencies of a project through the package.json file. It can also update and uninstall packages. In the package.json file, each dependency can specify a range of valid versions using the semantic versioning scheme, allowing developers to auto-update their packages while at the same time avoiding unwanted breaking changes. Some facts about NPM: At the time of writing this article, NPM has 580096 registered packages. The average rate of growth of this number is 291/day which outraces every other package registry. npm is open source The top npm packages in the decreasing order are: lodash, async, react, request, express. Installing NPM:To install NPM, it is required to install Node.js as NPM gets installed with Node.js automatically.Install Node.js. Checking and updating npm version:Version of npm installed on system can be checked using following syntax:Syntax: npm -v Checking npm version If the installed version is not latest, one can always update it using the given syntax:Syntax: npm update npm@latest -g. As npm is a global package, -g flag is used to update it globally. Creating a Node Project:To create a Node project, npm init is used in the folder in which user want to create project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file etc. After npm is done creating the project, a package.json file will be visible in project folder as a proof that the project has been initialized. npm init Installing Packages:After creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:Syntax: npm install package_name Example: Installing the express package into the project. Express is the web development framework used by the Node.Syntax: npm install express To use express in the Node, follow the below syntax:Syntax: var express = require('express'); Installing express module Example: To install a package globally (accessible by all projects in system), add an extra -g tag in syntax used to install the package.Installing nodemon package globally. npm install nodemon -g Installing nodemon package globally Controlling where the package gets installed:To install a package and simultaneously save it in package.json file (in case using Node.js), add –save flag. The –save flag is default in npm install command so it is equal to npm install package_name command.Example: npm install express --save By –save flag one can control where the packages are to be installed.–save-prod : Using this packages will appear in Dependencies which is also by default.–save-dev : Using this packages will get appear in devDependencies and will only be used in the development mode.Example: npm install node-color –save-dev –save-dev example If there is a package.json file with all the packages mentioned as dependencies already, just type npm install in terminal. npm will look at package.json file and install all the dependencies according to their mentioned versions. This command is typically used when a Node project is forked and cloned. The node_modules being a big folder is generally not pushed to a github repo and the cloner has to run npm install to install the dependencies. Note: NPM installs the dependencies in local mode (Default) which go to the node_modules directory present in the folder of Node application. To see all the locally installed modules use npm ls command. Uninstalling Packages:To uninstall packages using npm, follow the below syntax:Syntax: npm uninstall Example: To uninstall the express package Uninstalling express To uninstall global packages, follow the below syntax:Syntax: npm uninstall package_name -g Using Semantic Versioning to manage packages: To install a package of a specific version, mention the full and exact version in the package.json file. To install the latest version of the package, mention “*” in front of the dependency or “latest”. This will find the latest stable version of the module and install it. To install any version (stable one) above a given version, mention it like in the example below:“express”:”^4.1.1′′. in package.json file. The caret symbol (^) is used to tell the npm to find a version greater than 4.1.1 and install it. JavaScript-Misc Node.js JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Mar, 2022" }, { "code": null, "e": 1000, "s": 53, "text": "NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially released in Ja...
list::empty() and list::size() in C++ STL
23 Jun, 2022 Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. empty() function is used to check if the list container is empty or not. Syntax : listname.empty() Parameters : No parameters are passed. Returns : True, if list is empty False, Otherwise Examples: Input : list list{1, 2, 3, 4, 5}; list.empty(); Output : False Input : list list{}; list.empty(); Output : True Errors and Exceptions It has a no exception throw guarantee.Shows error when a parameter is passed. It has a no exception throw guarantee. Shows error when a parameter is passed. CPP // CPP program to illustrate// Implementation of empty() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; if (mylist.empty()) { cout << "True"; } else { cout << "False"; } return 0;} Output: True Application : Given a list of integers, find the sum of the all the integers. Input : 1, 5, 6, 3, 9, 2 Output : 26 Explanation - 1+5+6+3+9+2 = 26 Algorithm Check if the list is empty, if not add the front element to a variable initialised as 0, and pop the front element.Repeat this step until the list is empty.Print the final value of the variable. Check if the list is empty, if not add the front element to a variable initialised as 0, and pop the front element. Repeat this step until the list is empty. Print the final value of the variable. CPP // CPP program to illustrate// Application of empty() function#include <iostream>#include <list>using namespace std; int main(){ int sum = 0; list<int> mylist{ 1, 5, 6, 3, 9, 2 }; while (!mylist.empty()) { sum = sum + mylist.front(); mylist.pop_front(); } cout << sum; return 0;} Output: 26 size() function is used to return the size of the list container or the number of elements in the list container. Syntax : listname.size() Parameters : No parameters are passed. Returns : Number of elements in the container. Examples: Input : list list{1, 2, 3, 4, 5}; list.size(); Output : 5 Input : list list{}; list.size(); Output : 0 Errors and Exceptions It has a no exception throw guarantee.Shows error when a parameter is passed. It has a no exception throw guarantee. Shows error when a parameter is passed. CPP // CPP program to illustrate// Implementation of size() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; cout << mylist.size(); return 0;} Output: 5 Application : Given a list of integers, find the sum of the all the integers. Input : 1, 5, 6, 3, 9, 2 Output : 26 Explanation - 1+5+6+3+9+2 = 26 Algorithm Check if the size of the list is 0, if not add the front element to a variable initialised as 0, and pop the front element.Repeat this step until the list is empty.Print the final value of the variable. Check if the size of the list is 0, if not add the front element to a variable initialised as 0, and pop the front element. Repeat this step until the list is empty. Print the final value of the variable. CPP // CPP program to illustrate// Application of size() function#include <iostream>#include <list>using namespace std; int main(){ int sum = 0; list<int> mylist{ 1, 5, 6, 3, 9, 2 }; while (mylist.size() > 0) { sum = sum + mylist.front(); mylist.pop_front(); } cout << sum; return 0;} Output: 26 Let us see the differences in a tabular form -: mayank007rawa cpp-containers-library CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 304, "s": 53, "text": "Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operat...
Polymorphism in C++
22 Jun, 2022 The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. Like a man at the same time is a father, a husband and an employee. So the same person exhibits different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object-Oriented Programming. In C++, polymorphism is mainly divided into two types: Compile-time Polymorphism Runtime Polymorphism Types of Polymorphism Compile-time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. Compile-time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. Function Overloading: When there are multiple functions with the same name but different parameters, then the functions are said to be overloaded. Functions can be overloaded by changing the number of arguments or/and changing the type of arguments. Rules of Function Overloading CPP // C++ program for function overloading#include <bits/stdc++.h> using namespace std;class Geeks{ public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; }}; int main() { Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0;} Output: value of x is 7 value of x is 9.132 value of x and y is 85, 64 In the above example, a single function named func acts differently in three different situations, which is a property of polymorphism. Operator Overloading: C++ also provides the option to overload operators. For example, we can make use of the addition operator (+) for string class to concatenate two strings. We know that the task of this operator is to add two operands. So a single operator ‘+’, when placed between integer operands, adds them and when placed between string operands, concatenates them. Example: CPP // CPP program to illustrate// Operator Overloading#include<iostream>using namespace std; class Complex {private: int real, imag;public: Complex(int r = 0, int i =0) {real = r; imag = i;} // This is automatically called when '+' is used with // between two Complex objects Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; }}; int main(){ Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print();} Output: 12 + i9 In the above example, the operator ‘+’ is overloaded. Usually, this operator is used to add two numbers (integers or floating point numbers), but here the operator is made to perform the addition of two imaginary or complex numbers. To learn about operator overloading in detail, visit this link. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.Function overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.Function overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. Function overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. CPP // C++ program for function overriding #include <bits/stdc++.h>using namespace std; class base{public: virtual void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; }}; class derived:public base{public: void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; }}; //main functionint main(){ base *bptr; derived d; bptr = &d; //virtual function, binded at runtime (Runtime polymorphism) bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0;} Output: print derived class show base class To learn about runtime polymorphism in detail, visit this link. This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. TeShengLin RajivRanjanSahu mukulkumar3 kritipare308 bhaskartiwari258 sriparnxnw7 CPP-Functions cpp-operator-overloading C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ unordered_map in C++ STL Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Types of Operating Systems
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 633, "s": 52, "text": "The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life ex...
Matplotlib.axes.Axes.axvspan() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.axvspan() function in axes module of matplotlib library is used to add a vertical span (rectangle) across the axis. Syntax: Axes.axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs) Parameters: This method accept the following parameters that are described below: xmin: This parameter indicates the first X-axis coordinate of the vertical span rectangle in data units. xmax: This parameter indicates the second X-axis coordinate of the vertical span rectangle in data units. ymin: This parameter indicates the first Y-axis coordinate of the vertical span rectangle in relative Y-axis units . ymax: This parameter indicates the second Y-axis coordinate of the vertical span rectangle in relative Y-axis units. Returns: This returns the vertical span (rectangle) from (xmin, ymin) to (xmax, ymax). Below examples illustrate the matplotlib.axes.Axes.axhspan() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots() ax.axvspan(1.5, 2.5, facecolor ='g', alpha = 0.7) ax.set_title('matplotlib.axes.Axes.axvspan() Example') plt.show() Output: Example-2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.arange(-3, 4, .1)s = np.sin(np.pi * t) fig, ax = plt.subplots()ax.plot(t, s, color ='black')ax.axhline(y = 1, color ='black')ax.axvline(x = 1, color ='black')ax.axvline(x = 0, ymin = 0.75, linewidth = 8, color ='green')ax.axhline(y =.5, xmin = 0.25, xmax = 0.75, color ='black') ax.axhspan(0.25, 0.75, facecolor ='green', alpha = 0.7)ax.axvspan(1.25, 1.55, facecolor ='0.5', alpha = 0.5) ax.set_title('matplotlib.axes.Axes.axvspan() Example') plt.show() Output: Python-matplotlib 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text...
Maximum occurred integer in n ranges
06 Jul, 2022 Given n ranges of the form L and R, the task is to find the maximum occurred integer in all the ranges. If more than one such integer exists, print the smallest one. 0 <= Li, Ri < 1000000. Examples : Input : L1 = 1 R1 = 15 L2 = 4 R2 = 8 L3 = 3 R3 = 5 L4 = 1 R4 = 4 Output : 4 Input : L1 = 1 R1 = 15 L2 = 5 R2 = 8 L3 = 9 R3 = 12 L4 = 13 R4 = 20 L5 = 21 R5 = 30 Output : 5 Numbers having maximum occurrence i.e 2 are 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. The smallest number among all are 5. We traverse through all the ranges. Then for every range, we count frequencies, we make a hash table or hash map where we store every item. Then you travel through other ranges and increment the frequency of every item. The item with the highest frequency is our answer. But this solution requires time say there are N ranges and if M is the maximum number of elements in any of the ranges, then it’s going to take O(N*M) time. The hash table has the time complexity of insert and search and delete as O(1). So you can insert every item in the hash table and its frequency in O(1). We can do this in better time complexity if the ranges are fixed say (0 <= Li, Ri < 1000000). The trick here is we don’t want to travel every element of every range. We only want to travel through all ranges and we want to use the prefix sum technique to solve this problem. We create a vector/Arraylist/Array. All the values in the vector are initialized by zero (use the vector or ArrayList to avoid that extra line of .memset() in c++ or .fill() in java). So what we do is we loop through every range and mark the presence of the beginning of every range. We simply do this arr[L[i]]++. We also mark the end of this range by subtracting one from arr[R[i]+1]. As I discussed earlier, we Mark the presence of the beginning of every range as one. So if I do a prefix sum and if I Mark the beginning, all the values will be incremented by one after this element. Now we want to increment only till the end of the array. We do not want to increment other elements. Let say, L[] = {1, 2, 3} , R[] = {3, 5 , 7} 1. for this line arr[L[i]]++ the array becomes {0,1,1,1,0,0,0,0,......} 2. for this line arr[R[i]+1]– the array becomes {0,1,1,1,-1, 0, -1, 0,-1,......} 3. when we do prefix sum the array becomes {0,1,2,3,2,2,1,1,0...} When we do prefix sum, we’ll have the sum of elements after (1) incremented by one because I marked the beginning. Now I do not want this increment to happen to elements after (3). So if there’s a range one, two, three, the values from one, two, three should only be incremented by one or their frequency should be incremented by one. That is why we decrease the value of arr[R[i]+1]. So that elements after the end of this range have values minus one subtracted. That is how we nullify the impact of incrementing the value when I’m going to do the prefix. So when I’m going to do the prefix, I’m simply going to increment every value after the range, since I want to increment only in the range. That’s the idea of this algorithm. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find maximum occurred element in// given N ranges.#include <bits/stdc++.h>#define MAX 1000000using namespace std; // Return the maximum occurred element in all ranges.int maximumOccurredElement(int L[], int R[], int n){ // Initialising all element of array to 0. int arr[MAX]; memset(arr, 0, sizeof arr); // Adding +1 at Li index and subtracting 1 // at Ri index. int maxi=-1; for (int i = 0; i < n; i++) { arr[L[i]] += 1; arr[R[i] + 1] -= 1; if(R[i]>maxi){ maxi=R[i]; } } // Finding prefix sum and index having maximum // prefix sum. int msum = arr[0],ind; for (int i = 1; i < maxi+1; i++) { arr[i] += arr[i - 1]; if (msum < arr[i]) { msum = arr[i]; ind = i; } } return ind;} // Driven Programint main(){ int L[] = { 1, 4, 9, 13, 21 }; int R[] = { 15, 8, 12, 20, 30 }; int n = sizeof(L) / sizeof(L[0]); cout << maximumOccurredElement(L, R, n) << endl; return 0;} // Java program to find maximum occurred// element in given N ranges.import java.io.*; class GFG { static int MAX = 1000000; // Return the maximum occurred element in all ranges. static int maximumOccurredElement(int[] L, int[] R, int n) { // Initialising all element of array to 0. int[] arr = new int[MAX]; // Adding +1 at Li index and // subtracting 1 at Ri index. int maxi=-1; for (int i = 0; i < n; i++) { arr[L[i]] += 1; arr[R[i] + 1] -= 1; if(R[i]>maxi){ maxi=R[i]; } } // Finding prefix sum and index // having maximum prefix sum. int msum = arr[0]; int ind = 0; for (int i = 1; i < maxi+1; i++) { arr[i] += arr[i - 1]; if (msum < arr[i]) { msum = arr[i]; ind = i; } } return ind; } // Driver program static public void main(String[] args) { int[] L = { 1, 4, 9, 13, 21 }; int[] R = { 15, 8, 12, 20, 30 }; int n = L.length; System.out.println(maximumOccurredElement(L, R, n)); }} // This code is contributed by vt_m. # Python 3 program to find maximum occurred# element in given N ranges. MAX = 1000000 # Return the maximum occurred element# in all ranges.def maximumOccurredElement(L, R, n): # Initialising all element of array to 0. arr = [0 for i in range(MAX)] # Adding +1 at Li index and subtracting 1 # at Ri index. for i in range(0, n, 1): arr[L[i]] += 1 arr[R[i] + 1] -= 1 # Finding prefix sum and index # having maximum prefix sum. msum = arr[0] for i in range(1, MAX, 1): arr[i] += arr[i - 1] if (msum < arr[i]): msum = arr[i] ind = i return ind # Driver Codeif __name__ == '__main__': L = [1, 4, 9, 13, 21] R = [15, 8, 12, 20, 30] n = len(L) print(maximumOccurredElement(L, R, n)) # This code is contributed by# Sanjit_Prasad // C# program to find maximum// occurred element in given N ranges.using System; class GFG { static int MAX = 1000000; // Return the maximum occurred element in all ranges. static int maximumOccurredElement(int[] L, int[] R, int n) { // Initialising all element of array to 0. int[] arr = new int[MAX]; // Adding +1 at Li index and // subtracting 1 at Ri index. for (int i = 0; i < n; i++) { arr[L[i]] += 1; arr[R[i] + 1] -= 1; } // Finding prefix sum and index // having maximum prefix sum. int msum = arr[0]; int ind = 0; for (int i = 1; i < MAX; i++) { arr[i] += arr[i - 1]; if (msum < arr[i]) { msum = arr[i]; ind = i; } } return ind; } // Driver program static public void Main() { int[] L = { 1, 4, 9, 13, 21 }; int[] R = { 15, 8, 12, 20, 30 }; int n = L.Length; Console.WriteLine(maximumOccurredElement(L, R, n)); }} // This code is contributed by vt_m. <?php// PHP program to find maximum occurred// element in given N ranges.$MAX = 1000000; // Return the maximum occurred element// in all ranges.function maximumOccurredElement($L, $R, $n){ // Initialising all element // of array to 0. $arr = array(); for($i = 0; $i < $n; $i++) { $arr[] = "0"; } // Adding +1 at Li index and subtracting 1 // at Ri index. for ($i = 0; $i < $n; $i++) { $arr[$L[$i]] += 1; $arr[$R[$i] + 1] -= 1; } // Finding prefix sum and index // having maximum prefix sum. $msum = $arr[0]; for ($i = 1; $i <$n; $i++) { $arr[$i] += $arr[$i - 1]; if ($msum < $arr[$i]) { $msum = $arr[$i]; $ind = $i; } } return $ind;} // Driver Code$L = array(1, 4, 9, 13, 21);$R = array(15, 8, 12, 20, 30);$n = count($L); echo maximumOccurredElement($L, $R, $n); // This code is contributed by// Srathore?> <script> // JavaScript program to find maximum // occurred element in given N ranges. let MAX = 1000000; // Return the maximum occurred element in all ranges. function maximumOccurredElement(L, R, n) { // Initialising all element of array to 0. let arr = new Array(MAX); arr.fill(0); // Adding +1 at Li index and // subtracting 1 at Ri index. for (let i = 0; i < n; i++) { arr[L[i]] += 1; arr[R[i] + 1] -= 1; } // Finding prefix sum and index // having maximum prefix sum. let msum = arr[0]; let ind = 0; for (let i = 1; i < MAX; i++) { arr[i] += arr[i - 1]; if (msum < arr[i]) { msum = arr[i]; ind = i; } } return ind; } let L = [ 1, 4, 9, 13, 21 ]; let R = [ 15, 8, 12, 20, 30 ]; let n = L.length; document.write(maximumOccurredElement(L, R, n)); </script> 4 Time Complexity: O(n + MAX) Maximum Occurred Integer in N Ranges | DSA | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMaximum Occurred Integer in N Ranges | DSA | Programming Tutorials | 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 / 14:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=czJe_yO1ruI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Exercise: Try for 0 <= Li, Ri <= 1000000000. (Hint: Use stl map).Related Article: Maximum value in an array after m range increment operations This article is contributed by KaaL-EL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. vt_m Sanjit_Prasad sapnasingh4991 shreyashagrawal Lohith sai Andra Akanksha_Rai rameshtravel07 gabaa406 kaalel jitendranitrr13 sweetyty dungaajay123 hardikkoriintern Amazon prefix-sum Arrays Amazon prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 241, "s": 52, "text": "Given n ranges of the form L and R, the task is to find the maximum occurred integer in all the ranges. If more than one such integer exists, print the smallest one. 0 <= Li,...
How to create Responsive Profile Card using HTML and CSS ?
29 May, 2021 In this article, we are going to create a profile card from where a user can check out the basic details of other users and connect with them through different handles as well as can message the user. Approach: Firstly, we create a HTML file in which we do following things:Create a container which contains all the information.Add profile picture of the user.Add links of different social media handles.Add a button for messaging. Create a container which contains all the information. Add profile picture of the user. Add links of different social media handles. Add a button for messaging. Then, we create a CSS file in which we apply different types of styling property for our HTML tags. Finally, we link our CSS file to the HTML file using the link tag in the head section of the HTML. HTML Code: First, we create an HTML file(index.html).After creating the HTML file, we are going to give title to our webpage using <title> tag. It should be placed between the <head> tag.Then we link the css file that provide all the animations effect to our html. This is also placed in between <head> tag.Now we add a link from Google Fonts to use different type of font family in our project.Coming to the body section of our HTML code.Create a div in which we can store all of the images, links, buttons, headings and paragraphs.Then we create a div in which we add the image of the user.Another div is created, in this div we have to add the following tags:Heading tag is added to store the name of the user.A paragraph tag is added to store the username of the user.Then we added some social media links so that one can connect with this specified user.At last we have created a link for connecting the other using messaging service. First, we create an HTML file(index.html). After creating the HTML file, we are going to give title to our webpage using <title> tag. It should be placed between the <head> tag. Then we link the css file that provide all the animations effect to our html. This is also placed in between <head> tag. Now we add a link from Google Fonts to use different type of font family in our project. Coming to the body section of our HTML code.Create a div in which we can store all of the images, links, buttons, headings and paragraphs.Then we create a div in which we add the image of the user.Another div is created, in this div we have to add the following tags:Heading tag is added to store the name of the user.A paragraph tag is added to store the username of the user.Then we added some social media links so that one can connect with this specified user.At last we have created a link for connecting the other using messaging service. Create a div in which we can store all of the images, links, buttons, headings and paragraphs.Then we create a div in which we add the image of the user.Another div is created, in this div we have to add the following tags:Heading tag is added to store the name of the user.A paragraph tag is added to store the username of the user.Then we added some social media links so that one can connect with this specified user.At last we have created a link for connecting the other using messaging service. Create a div in which we can store all of the images, links, buttons, headings and paragraphs. Then we create a div in which we add the image of the user. Another div is created, in this div we have to add the following tags:Heading tag is added to store the name of the user.A paragraph tag is added to store the username of the user.Then we added some social media links so that one can connect with this specified user.At last we have created a link for connecting the other using messaging service. Heading tag is added to store the name of the user.A paragraph tag is added to store the username of the user.Then we added some social media links so that one can connect with this specified user.At last we have created a link for connecting the other using messaging service. Heading tag is added to store the name of the user. A paragraph tag is added to store the username of the user. Then we added some social media links so that one can connect with this specified user. At last we have created a link for connecting the other using messaging service. HTML <!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght@300&display=swap" rel="stylesheet"></head> <body> <div class="container"> <div class="user-image"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223165952/gfglogo.png" alt="this image contains user-image"> </div> <div class="content"> <h3 class="name">Geeks-For-Geeks</h3> <p class="username">@geeks_for_geeks</p> <div class="links"> <a class="facebook" href="https://www.facebook.com/geeksforgeeks.org/" target="_blank" title="GFG_facebook"> <i class="fab fa-facebook"></i> </a> <a class="git" href="https://github.com/topics/geeksforgeeks" title="GFG_github" target="_blank"> <i class="fab fa-github-square"></i> </a> <a class="linkedin" href="https://www.geeksforgeeks.org/tag/linkedin/" title="GFG_linkedin" target="_blank"> <i class="fab fa-linkedin"></i> </a> <a class="insta" href="https://www.instagram.com/geeks_for_geeks/?hl=en" target="_blank" title="GFG_instagram"> <i class="fab fa-instagram-square"></i> </a> </div> <p class="details"> A Computer Science portal for geeks </p> <a class="effect effect-4" href="#"> Message </a> </div> </div> <!-- This is link of adding small images which are used in the link section --> <script src="https://kit.fontawesome.com/704ff50790.js" crossorigin="anonymous"> </script></body> </html> CSS Code: CSS is used to give different types of animations and effect to our HTML page so that it looks interactive to all users. In CSS, we have to remind the following points- Restore all the browser effects. Use classes and ids to give effects to HTML elements. Use of nth-child selector feature of CSS to call different links. CSS *{ margin: 0; padding: 0; box-sizing: border-box;} /* Assigning all the same properties to the body */body{ height: 100vh; display: flex; justify-content: center; background-color: rgb(0, 0, 0); align-items: center;} .container{ width: 20em; background-color: rgb(255, 255, 255); overflow: hidden; border-radius: 1em; text-align: center; font-family: 'Open Sans Condensed', sans-serif; font-size: 1em;} .user-image{ padding: 3em 0; background-image: linear-gradient(70deg,#61A1DD,#0083FD);} .user-image img{ width: 7em; height: 7em; border-radius: 50%; box-shadow: 0 0.6em 1.8em ; object-fit: cover;} .content{ color: #565656; padding: 2.2em;} .name{ font-size: 1.5em; text-transform: uppercase;} .username{ font-size: 1em; color: #9e9e9e;} .links{ display: flex; justify-content: center; margin: 1.5em 0;} a{ text-decoration: none; color: #565656; transition: all 0.3s; font-size: 2em; margin-right: 1.2em;} a:last-child{ margin: 0;} .insta:hover{ color:rgb(255, 70, 101); transform: scale(2,2);} .git:hover{ color:rgb(0, 0, 0); transform: scale(2,2);} .linkedin:hover{ color:rgba(4, 0, 253, 0.842); transform: scale(2,2);} .facebook:hover{ color:rgb(4, 0, 255); transform: scale(2,2);} .details{ margin-bottom: 1.8em;} /* CSS for messagin link */ .effect { text-align: center; display: inline-block; position: relative; text-decoration: none; color: rgb(48, 41, 41); text-transform: capitalize; width: 100%; background-image: linear-gradient(60deg,#0083FD,#61A1DD); font-size: 1.2em; padding: 1em 3em; border-radius: 5em; overflow: hidden;} .effect.effect-4:before { content: "\f2b6"; font-family: FontAwesome; display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0; width: 100%; height: 100%; text-align: center; font-size: 1.8em; transform: scale(0, 1);}.effect.effect-4:hover { text-indent: -9999px;} .effect.effect-4:hover:before {transform: scale(1, 1);text-indent: 0;} Output: Code_Mech CSS-Questions CSS-Selectors HTML-Questions Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2021" }, { "code": null, "e": 229, "s": 28, "text": "In this article, we are going to create a profile card from where a user can check out the basic details of other users and connect with them through different handles as well...
Problem on permutations and combinations | Set 2
25 May, 2018 Prerequisite : Permutation and Combination Given a polygon of m sides, count number of triangles that can be formed using vertices of polygon. Answer : [m (m – 1)(m – 2) / 6]Explanation : There are m vertices in a polygon with m sides. We need to count different combinations of three points chosen from m. So answer is mC3 = m * (m – 1) * (m – 2) / 6Examples :Input: m = 3Output: 1We put value of m = 3, we get required no. of triangles = 3 * 2 * 1 / 6 = 1 Input : m = 6output : 20 Given a polygon of m sides, count number of diagonals that can be formed using vertices of polygon. Answer : [m (m – 3)] / 2.Explanation : We need to choose two vertices from polygon. We can choose first vertex m ways. We can choose second vertex in m-3 ways (Note that we can not choose adjacent two vertices to form a diagonal). So total number is m * (m – 3). This is twice the total number of combinations as we consider an diagonal edge u-v twice (u-v and v-u)Examples:Input m = 4output: 2We put the value of m = 4, we get the number of required diagonals = 4 * (4 – 3) / 2 = 2 Input: m = 5Output: 5 Count the total number rectangles that can be formed using m vertical lines and n horizontal lines Answer : (mC2*nC2).We need to choose two vertical lines and two horizontal lines. Since the vertical and horizontal lines are chosen independently, we multiply the result.Examples:Input: m = 2, n = 2Output: 1We have the total no of rectangles= 2C2*2C2= 1 * 1 = 1 Input: m = 4, n = 4Output: 36 There are ‘n’ points in a plane, out of which ‘m’ points are co-linear. Find the number of triangles formed by the points as vertices ? Number of triangles = nC3 – mC3Explanation : Consider the example n = 10, m = 4. There are 10 points, out of which 4 collinear. A triangle will be formed by any three of these ten points. Thus forming a triangle amounts to selecting any three of the 10 points. Three points can be selected out of the 10 points in nC3 ways.Number of triangles formed by 10 points when no 3 of them are co-linear = 10C3......(i)Similarly, the number of triangles formed by 4 points when no 3 of them are co-linear = 4C3........(ii) Since triangle formed by these 4 points are not valid, required number of triangles formed = 10C3 – 4C3 = 120 – 4 = 116 There are ‘n’ points in a plane out of which ‘m’ points are collinear, count the number of distinct straight lines formed by joining two points. Answer : nC2 – mC2 + 1Explanation : Number of straight lines formed by n points when none of them are col-linear = nC2Similarly, the number of straight lines formed by m points when none of them collinear = mC2m points are collinear and reduce in one line. Therefore we subtract mC2 and add 1.Hence answer = nC2 – mC2 +1Examples:Input : n = 4, m = 3output : 1We apply this formulaAnswer = 4C2 – 3C2 +1= 3 – 3 + 1= 1 More practice questions on permutation and combination :Quiz on Permutation and CombinationCombination and Permutation Practice Questions Permutation and Combination Combinatorial Engineering Mathematics GATE CS Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number itertools.combinations() module in Python to print all possible combinations Count of subsets with sum equal to X Difference between Propositional Logic and Predicate Logic Inequalities in LaTeX Arrow Symbols in LaTeX Set Notations in LaTeX
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2018" }, { "code": null, "e": 95, "s": 52, "text": "Prerequisite : Permutation and Combination" }, { "code": null, "e": 195, "s": 95, "text": "Given a polygon of m sides, count number of triangles that can b...
Underscore.js | _.isUndefined() with Examples
30 Jan, 2019 _.isUndefined() function: It checks if the parameter passed to it is undefined or not. If the parameter passed is undefined the it return true otherwise it returns false. We can even pass window elements to it. Syntax: _.isUndefined(value) Parameters:It takes only one argument which is the value or the variable that needs to be checked. Return value:It returns true if the value or parameter passed is undefined or else it returns false. Examples: Passing a variable to the _.isUndefined() function:The _.isUndefined() function takes the parameter passed to it. So, here it will check the variable ‘a’ which is passed. Since the value of ‘a’ is defined earlier as 10, so, it is a defined variable. Hence, the output will be false.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var a=10; console.log(_.isUndefined(a)); </script></body> </html>Output:Passing a number to the _.isUndefined() function:If we pass a number to the _.isUndefined() function then it checks whether that number is undefined or not. Since, we know all numbers are defined already. Therefore, the answer will be false.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(10)); </script></body> </html>Output:Passing “undefined” to _.isUndefined() function:The _.isUndefined() function takes the element passed to it which is “undefined” here. Since the parameter passed is undefined, therefore the output will be true.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(undefined)); </script></body> </html>Output:Passing missingVariable to the _.isUndefined() function:Here we are passing ‘window.missingVariable’ as a parameter. But here we have not defined any variable. So the missingVariable has no value. And hence, it is undefined. The output is true.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(window.missingVariable)); </script></body> </html>Output: Passing a variable to the _.isUndefined() function:The _.isUndefined() function takes the parameter passed to it. So, here it will check the variable ‘a’ which is passed. Since the value of ‘a’ is defined earlier as 10, so, it is a defined variable. Hence, the output will be false.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var a=10; console.log(_.isUndefined(a)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var a=10; console.log(_.isUndefined(a)); </script></body> </html> Output: Passing a number to the _.isUndefined() function:If we pass a number to the _.isUndefined() function then it checks whether that number is undefined or not. Since, we know all numbers are defined already. Therefore, the answer will be false.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(10)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(10)); </script></body> </html> Output: Passing “undefined” to _.isUndefined() function:The _.isUndefined() function takes the element passed to it which is “undefined” here. Since the parameter passed is undefined, therefore the output will be true.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(undefined)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(undefined)); </script></body> </html> Output: Passing missingVariable to the _.isUndefined() function:Here we are passing ‘window.missingVariable’ as a parameter. But here we have not defined any variable. So the missingVariable has no value. And hence, it is undefined. The output is true.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(window.missingVariable)); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> console.log(_.isUndefined(window.missingVariable)); </script></body> </html> Output: NOTE: These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows: <!-- Write HTML code here --><script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> JavaScript - Underscore.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2019" }, { "code": null, "e": 54, "s": 28, "text": "_.isUndefined() function:" }, { "code": null, "e": 115, "s": 54, "text": "It checks if the parameter passed to it is undefined or not." }, { "code":...
Finding Similar Type of Names | Fuzzy Search in SQL
10 May, 2021 Fuzzy Search :A technique of finding the strings that match a pattern approximately (rather than exactly). Users / Reviewers often capture names inaccurately. Typing mistake is a very common mistake that reviewer does while capturing the names which leads to inconsistency in Data. But sometimes, we need to search or match this inaccurate data anyway. For example, users should match existing customer records rather than creating unwanted duplicates. Problem Statement :Finding all kind of error types that described in the below table e.g. Spelling Mistake, Incomplete Name, Formatting Issue, Suffix Missing. Approach to solve :SOUNDEX() Function can find the inconsistency in names. SOUNDEX() can evaluate the similarity of two names. SOUNDEX() only works well when we do have 1 or 2 tokens. Names generally contain 1-2 tokens, so it works fine with Name. But if we want to find similar names for the company then it’s not that useful as it contains multiple tokens. Data :Benjamin Sheriff and Benjamin Sherrif where FirstName is same but any of the LastName has a spelling error. Likewise, there are many errors in this data like formatting issues, incomplete names. Code :Case-1: FirstName is exact the same but LastName is a similar type.Case-2: LastName is exact the same but FirstName is a similar type. Let’s discuss it one by one as follows. Case-1 : FirstName is exact the same but LastName is similar type : select distinct ss.firstname,ss.lastname,sd.firstname,sd.lastname from load as ss, load as sd where ss.firstName=sd.firstName and SOUNDEX(ss.lastName)=SOUNDEX(sd.lastname) and left(ss.lastname,2)=left(sd.lastname,2) and ss.lastName<>sd.lastName Output : Case-2 :LastName is exact same but FirstName is similar type : select distinct ss.lastname,ss.firstname,sd.lastname,sd.firstname from load as ss, load as sd where ss.lastname=sd.lastname and SOUNDEX(ss.firstname)=SOUNDEX(sd.firstname) and left(ss.firstname,2)=left(sd.firstname,2) and ss.firstname<>sd.firstname Output : Reference :Github Link – https://github.com/SuryaSD/Finding-Similar-Types-of-Names-Fuzzy-Search DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL SQL | Sub queries in From Clause What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT RANK() Function in SQL Server SQL Query to Compare Two Dates SQL Query to Convert Rows to Columns in SQL Server
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2021" }, { "code": null, "e": 481, "s": 28, "text": "Fuzzy Search :A technique of finding the strings that match a pattern approximately (rather than exactly). Users / Reviewers often capture names inaccurately. Typing mistake i...
Reverse first K elements of given linked list - GeeksforGeeks
22 Jun, 2021 Given a pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by changing links between nodes. check also Reversal of a linked list Examples: Input : 1->2->3->4->5->6->7->8->9->10->NULL k = 3 Output :3->2->1->4->5->6->7->8->9->10->NULL Input :10->18->20->25->35->NULL k = 2 Output :18->10->20->25->35->NULL Explanation of the method: suppose linked list is 1->2->3->4->5->NULL and k=31) Traverse the linked list till K-th point. 2) Break the linked list in to two parts from k-th point. After partition linked list will look like 1->2->3->NULL & 4->5->NULL 3) Reverse first part of the linked list leave second part as it is 3->2->1->NULL and 4->5->NULL 4) Join both the parts of the linked list, we get 3->2->1->4->5->NULLA pictorial representation of how the algorithm works C++ Java Python C# Javascript // C++ program for reversal of first k elements// of given linked list#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to reverse first k elements of linked list */static void reverseKNodes(struct Node** head_ref, int k){ // traverse the linked list until break // point not meet struct Node* temp = *head_ref; int count = 1; while (count < k) { temp = temp->next; count++; } // backup the joint point struct Node* joint_point = temp->next; temp->next = NULL; // break the list // reverse the list till break point struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } // join both parts of the linked list // traverse the list until NULL is not // found *head_ref = prev; current = *head_ref; while (current->next != NULL) current = current->next; // joint both part of the list current->next = joint_point;} /* Function to push a node */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;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} /* Driver program to test above function*/int main(){ // Create a linked list 1->2->3->4->5 struct Node* head = NULL; push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); // k should be less than the // numbers of nodes int k = 3; cout << "\nGiven list\n"; printList(head); reverseKNodes(&head, k); cout << "\nModified list\n"; printList(head); return 0;} // Java program for reversal of first k elements// of given linked listclass Sol{ // Link list nodestatic class Node{ int data; Node next;}; // Function to reverse first k elements of linked liststatic Node reverseKNodes( Node head_ref, int k){ // traverse the linked list until break // point not meet Node temp = head_ref; int count = 1; while (count < k) { temp = temp.next; count++; } // backup the joint point Node joint_point = temp.next; temp.next = null; // break the list // reverse the list till break point Node prev = null; Node current = head_ref; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } // join both parts of the linked list // traverse the list until null is not // found head_ref = prev; current = head_ref; while (current.next != null) current = current.next; // joint both part of the list current.next = joint_point; return head_ref;} // Function to push a nodestatic 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;} // Function to print linked liststatic void printList( Node head){ Node temp = head; while (temp != null) { System.out.printf("%d ", temp.data); temp = temp.next; }} // Driver program to test above functionpublic static void main(String args[]){ // Create a linked list 1.2.3.4.5 Node head = null; head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); // k should be less than the // numbers of nodes int k = 3; System.out.print("\nGiven list\n"); printList(head); head = reverseKNodes(head, k); System.out.print("\nModified list\n"); printList(head);}} // This code is contributed by Arnab Kundu # Python program for reversal of first k elements# of given linked list # Node of a linked listclass Node: def __init__(self, next = None, data = None): self.next = next self.data = data # Function to reverse first k elements of linked listdef reverseKNodes(head_ref, k) : # traverse the linked list until break # point not meet temp = head_ref count = 1 while (count < k): temp = temp.next count = count + 1 # backup the joint point joint_point = temp.next temp.next = None # break the list # reverse the list till break point prev = None current = head_ref next = None while (current != None): next = current.next current.next = prev prev = current current = next # join both parts of the linked list # traverse the list until None is not # found head_ref = prev current = head_ref while (current.next != None): current = current.next # joint both part of the list current.next = joint_point return head_ref # Function to push a nodedef push(head_ref, new_data) : new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Function to print linked listdef printList( head) : temp = head while (temp != None): print(temp.data, end = " ") temp = temp.next # Driver program to test above function # Create a linked list 1.2.3.4.5head = Nonehead = push(head, 5)head = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1) # k should be less than the# numbers of nodesk = 3 print("\nGiven list")printList(head) head = reverseKNodes(head, k) print("\nModified list")printList(head) # This code is contributed by Arnab Kundu // C# program for reversal of first k elements// of given linked listusing System; class GFG{ // Link list nodepublic class Node{ public int data; public Node next;}; // Function to reverse first k elements of linked liststatic Node reverseKNodes(Node head_ref, int k){ // traverse the linked list until break // point not meet Node temp = head_ref; int count = 1; while (count < k) { temp = temp.next; count++; } // backup the joint point Node joint_point = temp.next; temp.next = null; // break the list // reverse the list till break point Node prev = null; Node current = head_ref; Node next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } // join both parts of the linked list // traverse the list until null is not // found head_ref = prev; current = head_ref; while (current.next != null) current = current.next; // joint both part of the list current.next = joint_point; return head_ref;} // Function to push a nodestatic 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;} // Function to print linked liststatic void printList( Node head){ Node temp = head; while (temp != null) { Console.Write("{0} ", temp.data); temp = temp.next; }} // Driver Codepublic static void Main(String []args){ // Create a linked list 1.2.3.4.5 Node head = null; head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); // k should be less than the // numbers of nodes int k = 3; Console.Write("Given list\n"); printList(head); head = reverseKNodes(head, k); Console.Write("\nModified list\n"); printList(head);}} // This code is contributed by Princi Singh <script> // Javascript program for reversal of first k elements// of given linked list // Link list nodeclass Node{ constructor() { this.data = 0; this.next = null; }}; // Function to reverse first k elements of linked listfunction reverseKNodes(head_ref, k){ // traverse the linked list until break // point not meet var temp = head_ref; var count = 1; while (count < k) { temp = temp.next; count++; } // backup the joint point var joint_point = temp.next; temp.next = null; // break the list // reverse the list till break point var prev = null; var current = head_ref; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } // join both parts of the linked list // traverse the list until null is not // found head_ref = prev; current = head_ref; while (current.next != null) current = current.next; // joint both part of the list current.next = joint_point; return head_ref;} // Function to push a nodefunction push( head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to print linked listfunction printList( head){ var temp = head; while (temp != null) { document.write(temp.data+ " "); temp = temp.next; }} // Driver Code// Create a linked list 1.2.3.4.5var head = null;head = push(head, 5);head = push(head, 4);head = push(head, 3);head = push(head, 2);head = push(head, 1);// k should be less than the// numbers of nodesvar k = 3;document.write("Given list<br>");printList(head);head = reverseKNodes(head, k);document.write("<br>Modified list<br>");printList(head); </script> Output: Given list 1 2 3 4 5 Modified list 3 2 1 4 5 Time Complexity : O(n) YouTubeGeeksforGeeks506K subscribersReverse first K elements of given linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xSKFS5OA5JQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> VishalBachchas andrew1234 princi singh nidhi_biet rutvik_56 Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Real-time application of Data Structures Program to implement Singly Linked List in C++ using class Delete a node in a Doubly Linked List Insert a node at a specific position in a linked list Linked List Implementation in C# Priority Queue using Linked List
[ { "code": null, "e": 26313, "s": 26285, "text": "\n22 Jun, 2021" }, { "code": null, "e": 26538, "s": 26313, "text": "Given a pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by chang...
Bash Scripting - For Loop - GeeksforGeeks
15 Feb, 2022 Since BASH is a command-line language, we get some pretty feature-rich experience to leverage the programming skills to perform tasks in the terminal. We can use loops and conditional statements in BASH scripts to perform some repetitive and tricky problems in a simple programmatic way. In this article, we are going to focus on the for loop in BASH scripts. There are a couple of ways to use for loops depending on the use case and the problem it is trying to automate. Simple For loop Range-based for loop Array iteration for loops C-Styled for loops Infinite for loop To execute a for loop we can write the following syntax: #!/bin/usr/env bash for n in a b c; do echo $n done The above command will iterate over the specified elements after the in keyword one by one. The elements can be numbers, strings, or other forms of data. We can use range-based for loops. In this type of loop, we can specify the number to start, to stop, and to increment at every iteration(optional) in the statement. There are two ways you can do this i.e. by mentioning the increment/decrementer value and by incrementing by one by default. The syntax looks like this: #!/bin/usr/env bash for n in {1..5}; do echo $n done In the above code, we use the “{}” to specify a range of numbers. Inside the curly braces, we specify the start point followed by two dots and an endpoint. By default, it increments by one. Hence we print 5 numbers from 1 to 5 both inclusive. #!/bin/usr/env bash for n in {1..5..2}; do echo $n done Here we can see that the loop incremented by 2 units as mentioned in the curly braces. Thus this makes working with numbers very easy and convenient. This can also be used with alphabetical characters. NOTE: We cannot use variables inside the curly braces, so we will have to hardcode the values. To use the variables, we see the traditional C-styled for loops in the next few sections. We can iterate over arrays conveniently in bash using for loops with a specific syntax. We can use the special variables in BASH i.e @ to access all the elements in the array. Let’s look at the code: #!/bin/usr/env bash s=("football" "cricket" "hockey") for n in ${s[@]}; do echo $n done We can iterate over the array elements using the @ operator that gets all the elements in the array. Thus using the for loop we iterate over them one by one. We use the variable ${variable_name[@]} in which, the curly braces here expand the value of the variable “s” here which is an array of strings. Using the [@] operator we access all the elements and thus iterate over them in the for a loop. Here, the “n” is the iterator hence, we can print the value or do the required processing on it. As said earlier, we need to use the variables inside the for loops to iterate over a range of elements. And thus, the C-styled for loops play a very important role. Let’s see how we use them. #!/bin/usr/env bash n=7 for (( i=1 ; i<=$n ; i++ )); do echo $i done As we can see we can dynamically use the value of the range of end conditions. Remember the spaces between the double braces might be intentional and are part of the syntax. C-styled for loops are the loops that have 3 parts, the initializing iterator, the incrementor/decrementer, and the end condition. In the syntax above, we have initialized the loop iterator/counter to 1 that can be anything as per choice. The second part is the end condition, here we have used the variable “n” which is initialized before the for loop and thus we use the simple $ operator to get the value of the variable. Finally, we have the incrementor/decrementer which changes the iterator/counter to a value that can be anything but in the example, we have used the unary operator (++) to increment the value by one which is equivalent to “i=i+1”. Thus we can use statements like i+=2, i–,++i, and so on and so forth. We don’t use this often but it is sometimes useful to get certain things working. The syntax is quite easy and similar to the C-styled for loops. #!/bin/usr/env bash n=4 for (( ; ; )); do if [ $n -eq 9 ];then break fi echo $n ((n=n+1)) done As we can see the for loop has no conditions and this loops forever but we have a condition statement to check that it doesn’t go on forever. We use the break statement inside the if statement so as to get out of the loop and stop iterating with the iterator. We have used the incrementor to increment the variable in the loop otherwise the loop is infinite. Of course, we need some logic to break out of the loop and that is why we need to use the if conditional statement. rkbhola5 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction nohup Command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Array Basics in Shell Scripting | Set 1
[ { "code": null, "e": 24528, "s": 24500, "text": "\n15 Feb, 2022" }, { "code": null, "e": 24888, "s": 24528, "text": "Since BASH is a command-line language, we get some pretty feature-rich experience to leverage the programming skills to perform tasks in the terminal. We can use l...
How to find the intersection of two arrays in java?
To find the intersection of two arrays in java use two loops. The outer loop is to iterate the elements of the first array whereas, the second loop is to iterate the elements of the second array. Within the second loop compare the elements of the two arrays: Live Demo public class IntersectionOfTwoArrays { public static void main(String args[]) { int myArray1[] = {23, 36, 96, 78, 55}; int myArray2[] = {78, 45, 19, 73, 55}; System.out.println("Intersection of the two arrays ::"); for(int i = 0; i<myArray1.length; i++ ) { for(int j = 0; j<myArray2.length; j++) { if(myArray1[i]==myArray2[j]) { System.out.println(myArray2[j]); } } } } } Intersection of the two arrays :: 78 55
[ { "code": null, "e": 1321, "s": 1062, "text": "To find the intersection of two arrays in java use two loops. The outer loop is to iterate the elements of the first array whereas, the second loop is to iterate the elements of the second array. Within the second loop compare the elements of the two ar...
How to draw a line following mouse coordinates with tkinter?
To draw a line following mouse coordinates, we need to create a function to capture the coordinates of each mouse-click and then draw a line between two consecutive points. Let's take an example and see how it can be done. Import the tkinter library and create an instance of tkinter frame. Import the tkinter library and create an instance of tkinter frame. Set the size of the frame using geometry method. Set the size of the frame using geometry method. Create a user-defined method "draw_line" to capture the x and y coordinates of each mouse click. Then, use the create_line() method of Canvas to draw a line between two consecutive points. Create a user-defined method "draw_line" to capture the x and y coordinates of each mouse click. Then, use the create_line() method of Canvas to draw a line between two consecutive points. Bind the left-click of the mouse with the draw_line method. Bind the left-click of the mouse with the draw_line method. Finally, run the mainloop of the application window. Finally, run the mainloop of the application window. # Import the library import tkinter as tk # Create an instance of tkinter win = tk.Tk() # Window size win.geometry("700x300") # Method to draw line between two consecutive points def draw_line(e): x, y = e.x, e.y if canvas.old_coords: x1, y1 = canvas.old_coords canvas.create_line(x, y, x1, y1, width=5) canvas.old_coords = x, y canvas = tk.Canvas(win, width=700, height=300) canvas.pack() canvas.old_coords = None # Bind the left button the mouse. win.bind('<ButtonPress-1>', draw_line) win.mainloop() It will track the left-clicks of the mouse and draw a line between each two consecutive points.
[ { "code": null, "e": 1285, "s": 1062, "text": "To draw a line following mouse coordinates, we need to create a function to capture the coordinates of each mouse-click and then draw a line between two consecutive points. Let's take an example and see how it can be done." }, { "code": null, ...
A Protocol Using Go-Back-N
Go-Back-N protocol, also called Go-Back-N Automatic Repeat reQuest, is a data link layer protocol that uses a sliding window method for reliable and sequential delivery of data frames. It is a case of sliding window protocol having to send window size of N and receiving window size of 1. Go – Back – N ARQ provides for sending multiple frames before receiving the acknowledgment for the first frame. The frames are sequentially numbered and a finite number of frames. The maximum number of frames that can be sent depends upon the size of the sending window. If the acknowledgment of a frame is not received within an agreed upon time period, all frames starting from that frame are retransmitted. The size of the sending window determines the sequence number of the outbound frames. If the sequence number of the frames is an n-bit field, then the range of sequence numbers that can be assigned is 0 to 2n−1. Consequently, the size of the sending window is 2n−1. Thus in order to accommodate a sending window size of 2n−1, a n-bit sequence number is chosen. The sequence numbers are numbered as modulo-n. For example, if the sending window size is 4, then the sequence numbers will be 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, and so on. The number of bits in the sequence number is 2 to generate the binary sequence 00, 01, 10, 11. The size of the receiving window is 1. begin frame s; //s denotes frame to be sent frame t; //t is temporary frame S_window = power(2,m) – 1; //Assign maximum window size SeqFirst = 0; // Sequence number of first frame in window SeqN = 0; // Sequence number of Nth frame window while (true) //check repeatedly do Wait_For_Event(); //wait for availability of packet if ( Event(Request_For_Transfer)) then //check if window is full if (SeqN–SeqFirst >= S_window) then doNothing(); end if; Get_Data_From_Network_Layer(); s = Make_Frame(); s.seq = SeqN; Store_Copy_Frame(s); Send_Frame(s); Start_Timer(s); SeqN = SeqN + 1; end if; if ( Event(Frame_Arrival) then r = Receive_Acknowledgement(); if ( AckNo > SeqFirst && AckNo < SeqN ) then while ( SeqFirst <= AckNo ) Remove_copy_frame(s.seq(SeqFirst)); SeqFirst = SeqFirst + 1; end while Stop_Timer(s); end if end if // Resend all frames if acknowledgement havn’t been received if ( Event(Time_Out)) then TempSeq = SeqFirst; while ( TempSeq < SeqN ) t = Retrieve_Copy_Frame(s.seq(SeqFirst)); Send_Frame(t); Start_Timer(t); TempSeq = TempSeq + 1; end while end if end Begin frame f; RSeqNo = 0; // Initialise sequence number of expected frame while (true) //check repeatedly do Wait_For_Event(); //wait for arrival of frame if ( Event(Frame_Arrival) then Receive_Frame_From_Physical_Layer(); if ( Corrupted ( f.SeqNo ) doNothing(); else if ( f.SeqNo = RSeqNo ) then Extract_Data(); Deliver_Data_To_Network_Layer(); RSeqNo = RSeqNo + 1; Send_ACK(RSeqNo); end if end if end while end
[ { "code": null, "e": 1351, "s": 1062, "text": "Go-Back-N protocol, also called Go-Back-N Automatic Repeat reQuest, is a data link layer protocol that uses a sliding window method for reliable and sequential delivery of data frames. It is a case of sliding window protocol having to send window size o...
What are the differences between implicit and explicit waits in Selenium with python?
The differences between implicit and explicit wait are listed below − title_contains visibility_of_element_located presence_of_element_located title_is visibility_of element_selection_state_to_be presence_of_all_elements_located element_located_to_be_selected alert_is_present element_located_selection_state_to_b e staleness_of element_to_be_clickable invisibility_of_element_located frame_to_be_available_and_switch_to _it text_to_be_present_in_element_value text_to_be_present_in_element element_to_be_selected driver.implicitly_wait(2) w = WebDriverWait(driver, 7) w.until(expected_conditions.presence_of_ele ment_located((By.ID, "Tutorialspoint")))
[ { "code": null, "e": 1132, "s": 1062, "text": "The differences between implicit and explicit wait are listed below −" }, { "code": null, "e": 1147, "s": 1132, "text": "title_contains" }, { "code": null, "e": 1177, "s": 1147, "text": "visibility_of_element_loca...
The essential guide to Sample Ratio Mismatch for your A/B tests | by Iqbal Ali | Towards Data Science
Lack of data integrity is a common issue for experiments. They’re especially common when dealing with redirect tests, single-page applications, or other complex setups. It doesn’t matter how long you’ve been building tests; these problems just happen. So, given this fact, what can we do about it? First (and most importantly), we need to be tracking the data integrity of our experiments very closely. So, if there is an issue, we know about it sooner rather than later. One essential (and simple) check anyone can perform is the Sample Ratio Mismatch (SRM) check. You don’t have to be an analyst or data scientist to do this. In fact, many of the problems I’ve come across with tests were identified by product owners. In this article, I’ll give you a practical overview of what SRM is and the various ways to check it. With this knowledge, you can go away and integrate it into your own experiment process. Before we start, I must stress one point: while SRM catches many problems, it doesn’t highlight every possible problem with your setup. This is just the minimum you should be doing. Suppose you have an A/B test where the expectation is a 50/50 split... But suppose what you actually see is something like this... Note that the sample sizes don’t match. This is what we mean by “sample ratio mismatch” — i.e. the ratios of samples don’t match our expectation (a 50/50 split). Having a skew like this can invalidate your test. Before we go further, we need to identify a couple of rules to follow. The first of these rules is to prioritise SRM checks with “users” rather “visits”. That’s because it’s “users” who are assigned to experiments. In comparison, “visits” are the number of “sessions” these users have made. We might actually expect a skew in visits if a variation encourages a user to return more (or less) often. So, does this mean that SRM with “visits” is always okay? Not necessarily. I’ve come across scenarios where defects caused users to drop visits in one variation more than another. It’s just that SRM with “visits” isn’t the “smoking gun” evidence of a problem that SRM with “users” is. Anyway, onto our second rule for checking Sample Ratio Mismatch. And that’s this: we need to be looking for problems frequently. Checking for SRM is not a one and done activity. We need to be checking our tests pretty much as soon as they launch, and then we should be checking regularly. New experiments should be treated like intensive care patients for at least the first week of launch. This rule immediately gives us a problem to overcome because the traffic volumes being interrogated could be really low. But there are ways to increase our certainty levels. We’ll cover this a little later in the article. First, let’s look at the easiest ways to identify a problem. The first and easiest way to identify a problem is by looking at the test assignment numbers. Some problems are so glaring; you can raise the alarm straight away without needing to do any math. For instance, if you see 1,000 users in one group and 100 in the other, you know there’s a problem. It might seem an obvious thing to point out, but it’s important not to assume that checking SRM is some sort of major activity. Just being able to easily see the numbers quickly could save you some major time. What’s more, once you develop a habit of regularly looking at these sorts of numbers, you develop an eye for spotting mismatches — especially the big ones. But suppose it’s closer? Suppose you have 10,000 users in the control group and 9,500 users in the variation. What do you do then? We can run a simple calculation to find the sample ratios. First, get the total sum of users assigned to the experiment... total_users_in_test = users_in_control + users_in_variation ...and then work out the percentage of users in each group. control = users_in_control / total_users_in_testvariation = users_variation / total_users_in_test You don’t have to work out both control and variation. Just one will do. For our example, the calculation: control = 10,000 / (10,000 + 9,000) = 0.5263variation = 9,500 / (10,000 + 9,000) = 0.4737 So, 52.63% of users are in the control group, and 47.37% are in the variation. Now, we might expect to see a certain amount of mismatch during the early days of an experiment, but the above looks pretty suspicious. How can we improve our level of certainty? It’s time to employ some statistics... Statistics are ways of describing data in useful ways. We have two samples: the traffic volumes for control and variation groups. It would be useful to know the likelihood that the differences between the numbers are outside of normal chance. We can do this using the chi-squared test of independence. This test tells us that, given two samples, the probability that the samples are independent. You actually don’t need to know the formula for calculating Chi (though I’ll go through it a little later), as it’s super simple using python: observed = [ 170471, 171662 ]total_traffic= sum(observed)expected = [ total_traffic/2, total_traffic/2 ]from scipy.stats import chisquarechi = chisquare(observed, f_exp=expected)print(chi) The “observed” variable lists two values: number of users in control and number of users in variation. The “expected” variable is also a list of two values: the number of users we expect for each group. The volume we’re expecting is half of the total traffic in each. That’s the total traffic, divided by two. We need the “chi-square” module from scipy.stats. After that, we just feed the numbers in. The output we get is: Power_divergenceResult(statistic=4.145992932573005, pvalue=0.041733172643879435) This is a tuple, where the first item is the chi-squared statistic, and the second item is the p-value. Normally, one would look for a p-value of 0.05 or less to determine independence (and, in our case, proof of SRM). The problem with 0.05 is that it’s not strict enough for our purposes. Using this might give us a false signal of a problem. Michael Lindon (part of the Optimizely team) goes into detail about this in the following article. What we need is to be stricter for our test of independence. A value below 0.01 should be enough. With our Python example, we can write up a conditional statement to make it easier to read: if chi[1] < 0.01: print('Warning. SRM may be present.')else: print('Probably no SRM.') By the way, chi[1] means we access the p-value from the tuple. Our full script looks like this. Using our example, we don’t have hard evidence of SRM. One more thing to add is that I like to look at cumulative views. The more traffic we have, the closer the two groups should align in terms of the sample split: Above is a pretty typical view of sample ratios. These cumulative views can be useful for determining when SRM began occurring if a defect is introduced partway through the runtime of an experiment. I realise that many reading this may not be familiar with python. So, here’s an example using a spreadsheet (works in Google Sheets or Excel): Using the CHITEST formula, we can pass the two sets of values: observed, and expected. =CHITEST(observed_cell_range,expected_cell_range) The first range of numbers is the “observed” values for control and variation. The second range is for the “expected” (total divided by two). The output of the formula is the P-value. After that, the rules are the same as our python example: less than 0.01 indicates a possible SRM. For those who really want to dig into the Chi-Test formula, here it is: The chi statistic is the sum of each of the observed values minus the expected values squared, divided by the expected. Huh? Let’s use a spreadsheet to break this down: The columns: Observed: the control and variation traffic volumes, respectively. Expected: the expected values for each— i.e. the observed total divided by 2. Difference: the observed value minus the expected Difference Squared: the difference multiplied by itself Difference Squared / Expected: difference squared divided by the expected. Each row is a variation group. Eg. control and variation (A/B). After this, we’re ready to find the Chi Statistic, which is just a sum of the Diff Squared/Expected (as in the formula above): How do we get a p-value from this? Well, there’s one more thing we need first: that’s the degree of freedom, which is calculated as: Degree of Freedom = (rows − 1) × (columns − 1) In our case, our degree of freedom is 1 (two rows for test and control and two columns for observed and expected). We can then use a p-value table to locate our score and find the associated p-value: Or use a spreadsheet function: =CHISQ.DIST.RT( chi_statistic, degrees_of_freedom) This function gives us the precise p-value. Our final spreadsheet looks like this: Of course, you can circumvent all of this by using the CHITEST function as shown earlier. Checking the validity of the traffic is super easy using Chi. There’s really no excuse not to do it. Besides, you could really save yourself a lot of time by doing this simple check. Once you’re doing this regularly, you can start going further by adding more checks for data validation. This is really the beginning. But it’s an essential beginning. Having said all of that, be wary of crying wolf. That can be as damaging to your experimentation process as data validity issues themselves. I’m usually wary of declaring a problem during the first day of the experiment launch unless there’s a glaring issue. Do this often, and you’ll become an expert at determining SRM issues early. I’m Iqbal Ali, writer of comics, former Head of Optimisation at Trainline, creator of the A/B Decisions tool, and a freelance CRO specialist and consultant. I help companies with their experimentation programs, designing, developing, training, and setting up experiment processes. Here’s my LinkedIn if you want to connect. Or follow me here on Medium.
[ { "code": null, "e": 424, "s": 172, "text": "Lack of data integrity is a common issue for experiments. They’re especially common when dealing with redirect tests, single-page applications, or other complex setups. It doesn’t matter how long you’ve been building tests; these problems just happen." ...
Text preprocessing steps and universal reusable pipeline | by Maksym Balatsko | Towards Data Science
Before feeding any ML model some kind data, it has to be properly preprocessed. You must have heard the byword: Garbage in, garbage out (GIGO). Text is a specific kind of data and can't be directly fed to most ML models, so before feeding it to a model you have to somehow extract numerical features from it, in another word vectorize. Vectorization is not the topic of this tutorial, but the main thing you have to understand is that GIGO is also applicable on vectorization too, you can extract qualitative features only from the qualitatively preprocessed text. Things we are going to discuss: TokenizationCleaningNormalizationLemmatizationSteaming Tokenization Cleaning Normalization Lemmatization Steaming Finally, we’ll create a reusable pipeline, which you’ll be able to use in your applications. Kaggle kernel: https://www.kaggle.com/balatmak/text-preprocessing-steps-and-universal-pipeline Let’s assume this example text: An explosion targeting a tourist bus has injured at least 16 people near the Grand Egyptian Museum, next to the pyramids in Giza, security sources say E.U.South African tourists are among the injured. Most of those hurt suffered minor injuries, while three were treated in hospital, N.A.T.O. say.http://localhost:8888/notebooks/Text%20preprocessing.ipynb@nickname of twitter user and his email is email@gmail.com . A device went off close to the museum fence as the bus was passing on 16/02/2012. Tokenization - text preprocessing step, which assumes splitting text into tokens(words, sentences, etc.) Seems like you can use somkeind of simple seperator to achieve it, but you don’t have to forget that there are a lot of different situations, where separators just don’t work. For example, . separator for tokenization into sentences will fail if you have abbreviations with dots. So you have to have a more complex model to achieve good enough result. Commonly this problem is solved using nltk or spacy nlp libraries. NLTK: from nltk.tokenize import sent_tokenize, word_tokenizenltk_words = word_tokenize(example_text)display(f"Tokenized words: {nltk_words}") Output: Tokenized words: ['An', 'explosion', 'targeting', 'a', 'tourist', 'bus', 'has', 'injured', 'at', 'least', '16', 'people', 'near', 'the', 'Grand', 'Egyptian', 'Museum', ',', 'next', 'to', 'the', 'pyramids', 'in', 'Giza', ',', 'security', 'sources', 'say', 'E.U', '.', 'South', 'African', 'tourists', 'are', 'among', 'the', 'injured', '.', 'Most', 'of', 'those', 'hurt', 'suffered', 'minor', 'injuries', ',', 'while', 'three', 'were', 'treated', 'in', 'hospital', ',', 'N.A.T.O', '.', 'say', '.', 'http', ':', '//localhost:8888/notebooks/Text', '%', '20preprocessing.ipynb', '@', 'nickname', 'of', 'twitter', 'user', 'and', 'his', 'email', 'is', 'email', '@', 'gmail.com', '.', 'A', 'device', 'went', 'off', 'close', 'to', 'the', 'museum', 'fence', 'as', 'the', 'bus', 'was', 'passing', 'on', '16/02/2012', '.'] Spacy: import spacyimport en_core_web_smnlp = en_core_web_sm.load()doc = nlp(example_text)spacy_words = [token.text for token in doc]display(f"Tokenized words: {spacy_words}") Output: Tokenized words: ['\\n', 'An', 'explosion', 'targeting', 'a', 'tourist', 'bus', 'has', 'injured', 'at', 'least', '16', 'people', 'near', 'the', 'Grand', 'Egyptian', 'Museum', ',', '\\n', 'next', 'to', 'the', 'pyramids', 'in', 'Giza', ',', 'security', 'sources', 'say', 'E.U.', '\\n\\n', 'South', 'African', 'tourists', 'are', 'among', 'the', 'injured', '.', 'Most', 'of', 'those', 'hurt', 'suffered', 'minor', 'injuries', ',', '\\n', 'while', 'three', 'were', 'treated', 'in', 'hospital', ',', 'N.A.T.O.', 'say', '.', '\\n\\n', 'http://localhost:8888/notebooks', '/', 'Text%20preprocessing.ipynb', '\\n\\n', '@nickname', 'of', 'twitter', 'user', 'and', 'his', 'email', 'is', 'email@gmail.com', '.', '\\n\\n', 'A', 'device', 'went', 'off', 'close', 'to', 'the', 'museum', 'fence', 'as', 'the', 'bus', 'was', 'passing', 'on', '16/02/2012', '.', '\\n'] In spacy output tokenization, but not in nltk: {'E.U.', '\\n', 'Text%20preprocessing.ipynb', 'email@gmail.com', '\\n\\n', 'N.A.T.O.', 'http://localhost:8888/notebooks', '@nickname', '/'} In nltk but not in spacy: {'nickname', '//localhost:8888/notebooks/Text', 'N.A.T.O', ':', '@', 'gmail.com', 'E.U', 'http', '20preprocessing.ipynb', '%'} We see that spacy tokenized some weird stuff like \n, \n\n, but was able to handle URLs, emails and Twitter-like mentions. Also, we see that nltk tokenized abbreviations without the last . Cleaning is step assumes removing all undesirable content. Punctuation removal might be a good step, when punctuation does not brings additional value for text vectorization. Punctuation removal is better to be done after the tokenization step, doing it before might cause undesirable effects. Good choice for TF-IDF, Count, Binary vectorization. Let’s assume this text for this step: @nickname of twitter user, and his email is email@gmail.com . Before tokenization: text_without_punct = text_with_punct.translate(str.maketrans('', '', string.punctuation))display(f"Text without punctuation: {text_without_punct}") Output: Text without punctuation: nickname of twitter user and his email is emailgmailcom Here you can see that important symbols for correct tokenizations were removed. Now email can’t be properly detected. As you could mention from the Tokenization step, punctuation symbols were parsed as single tokens, so better way would be to tokenize first and then remove punctuation symbols. import spacyimport en_core_web_smnlp = en_core_web_sm.load()doc = nlp(text_with_punct)tokens = [t.text for t in doc]# python based removaltokens_without_punct_python = [t for t in tokens if t not in string.punctuation]display(f"Python based removal: {tokens_without_punct_python}")# spacy based removaltokens_without_punct_spacy = [t.text for t in doc if t.pos_ != 'PUNCT']display(f"Spacy based removal: {tokens_without_punct_spacy}") Python based removal result: ['@nickname', 'of', 'twitter', 'user', 'and', 'his', 'email', 'is', 'email@gmail.com'] Spacy based removal: ['of', 'twitter', 'user', 'and', 'his', 'email', 'is', 'email@gmail.com'] Here you see that python-based removal worked even better than spacy because spacy tagged @nicname as PUNCT part-of-speech. Stop words usually refers to the most common words in a language, which usually does not bring additional meaning. There is no single universal list of stop words used by all nlp tools because this term has a very fuzzy definition. Although the practice has shown, that this step is must have when preparing a text for indexing, but might be tricky for text classification purposes. Spacy stop words count: 312 NLTK stop words count: 179 Let’s assume this text for this step: This movie is just not good enough Spacy: import spacyimport en_core_web_smnlp = en_core_web_sm.load()text_without_stop_words = [t.text for t in nlp(text) if not t.is_stop]display(f"Spacy text without stop words: {text_without_stop_words}") Spacy text without stop words: ['movie', 'good'] NLTK: import nltknltk_stop_words = nltk.corpus.stopwords.words('english')text_without_stop_words = [t for t in word_tokenize(text) if t not in nltk_stop_words]display(f"nltk text without stop words: {text_without_stop_words}") NLTK text without stop words: ['This', 'movie', 'good', 'enough'] Here you see that nltk and spacy have different vocabulary size, so the results of filtering are different. But the main thing I want to underline is that the word not was filtered, which in most cases will be alright, but in the case when you want to determine the polarity of this sentence not will bring additional meaning. For such cases, you are able to set stop words you can ignore in spacy library. In the case of nltk you cat just remove or add custom words to nltk_stop_words, it is just a list. import en_core_web_smnlp = en_core_web_sm.load()customize_stop_words = [ 'not']for w in customize_stop_words: nlp.vocab[w].is_stop = Falsetext_without_stop_words = [t.text for t in nlp(text) if not t.is_stop]display(f"Spacy text without updated stop words: {text_without_stop_words}") Spacy text without updated stop words: ['movie', 'not', 'good'] Like any data text requires normalization. In case of text it is: Converting dates to textNumbers to textCurrency/Percent signs to textExpanding of abbreviations (content dependent) NLP — Natural Language Processing, Neuro-linguistic programming, Non-Linear programmingSpelling mistakes correction Converting dates to text Numbers to text Currency/Percent signs to text Expanding of abbreviations (content dependent) NLP — Natural Language Processing, Neuro-linguistic programming, Non-Linear programming Spelling mistakes correction To summarize, normalization is a conversion of any non-text information into textual equivalent. For this purposes exists a great library — normalize. I’ll show you the usage of this library from its README. This library is based on nltk package, so it expects nltk word tokens. Let’s assume this text for this step: On the 13 Feb. 2007, Theresa May announced on MTV news that the rate of childhod obesity had risen from 7.3-9.6% in just 3 years , costing the N.A.T.O £20m Code: from normalise import normaliseuser_abbr = { "N.A.T.O": "North Atlantic Treaty Organization"}normalized_tokens = normalise(word_tokenize(text), user_abbrevs=user_abbr, verbose=False)display(f"Normalized text: {' '.join(normalized_tokens)}") Output: On the thirteenth of February two thousand and seven , Theresa May announced on M T V news that the rate of childhood obesity had risen from seven point three to nine point six % in just three years , costing the North Atlantic Treaty Organization twenty million pounds The worst thing in this library is that for now you can’t disable some modules like abbreviation expanding, and it causes things like MTV -> M T V. But I have already added an appropriate issue on this repository, maybe it would be fixed in a while. Stemming is the process of reducing inflection in words to their root forms such as mapping a group of words to the same stem even if the stem itself is not a valid word in the Language. Lemmatization, unlike Stemming, reduces the inflected words properly ensuring that the root word belongs to the language. In Lemmatization root word is called Lemma. A lemma (plural lemmas or lemmata) is the canonical form, dictionary form, or citation form of a set of words. Let’s assume this text for this step: On the thirteenth of February two thousand and seven , Theresa May announced on M T V news that the rate of childhood obesity had risen from seven point three to nine point six % in just three years , costing the North Atlantic Treaty Organization twenty million pounds NLTK stemmer: import numpy as npfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenizetokens = word_tokenize(text)porter=PorterStemmer()# vectorizing function to able to call on list of tokensstem_words = np.vectorize(porter.stem)stemed_text = ' '.join(stem_words(tokens))display(f"Stemed text: {stemed_text}") Stemmed text: On the thirteenth of februari two thousand and seven , theresa may announc on M T V news that the rate of childhood obes had risen from seven point three to nine point six % in just three year , cost the north atlant treati organ twenti million pound NLTK lemmatization: import numpy as npfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizetokens = word_tokenize(text)wordnet_lemmatizer = WordNetLemmatizer()# vectorizing function to able to call on list of tokenslemmatize_words = np.vectorize(wordnet_lemmatizer.lemmatize)lemmatized_text = ' '.join(lemmatize_words(tokens))display(f"nltk lemmatized text: {lemmatized_text}") NLTK lemmatized text: On the thirteenth of February two thousand and seven , Theresa May announced on M T V news that the rate of childhood obesity had risen from seven point three to nine point six % in just three year , costing the North Atlantic Treaty Organization twenty million pound Spacy lemmatization: import en_core_web_smnlp = en_core_web_sm.load()lemmas = [t.lemma_ for t in nlp(text)]display(f"Spacy lemmatized text: {' '.join(lemmas)}") Spacy lemmatized text: On the thirteenth of February two thousand and seven , Theresa May announce on M T v news that the rate of childhood obesity have rise from seven point three to nine point six % in just three year , cost the North Atlantic Treaty Organization twenty million pound We see that spacy lemmatized much better than nltk, one of the examples risen -> rise, only spacy handled that. And now my favorite part! We are going to create a reusable pipeline, which you could use on any of your projects. import numpy as npimport multiprocessing as mpimport stringimport spacy import en_core_web_smfrom nltk.tokenize import word_tokenizefrom sklearn.base import TransformerMixin, BaseEstimatorfrom normalise import normalisenlp = en_core_web_sm.load()class TextPreprocessor(BaseEstimator, TransformerMixin): def __init__(self, variety="BrE", user_abbrevs={}, n_jobs=1): """ Text preprocessing transformer includes steps: 1. Text normalization 2. Punctuation removal 3. Stop words removal 4. Lemmatization variety - format of date (AmE - american type, BrE - british format) user_abbrevs - dict of user abbreviations mappings (from normalise package) n_jobs - parallel jobs to run """ self.variety = variety self.user_abbrevs = user_abbrevs self.n_jobs = n_jobs def fit(self, X, y=None): return self def transform(self, X, *_): X_copy = X.copy() partitions = 1 cores = mp.cpu_count() if self.n_jobs <= -1: partitions = cores elif self.n_jobs <= 0: return X_copy.apply(self._preprocess_text) else: partitions = min(self.n_jobs, cores) data_split = np.array_split(X_copy, partitions) pool = mp.Pool(cores) data = pd.concat(pool.map(self._preprocess_part, data_split)) pool.close() pool.join() return data def _preprocess_part(self, part): return part.apply(self._preprocess_text) def _preprocess_text(self, text): normalized_text = self._normalize(text) doc = nlp(normalized_text) removed_punct = self._remove_punct(doc) removed_stop_words = self._remove_stop_words(removed_punct) return self._lemmatize(removed_stop_words) def _normalize(self, text): # some issues in normalise package try: return ' '.join(normalise(text, variety=self.variety, user_abbrevs=self.user_abbrevs, verbose=False)) except: return text def _remove_punct(self, doc): return [t for t in doc if t.text not in string.punctuation] def _remove_stop_words(self, doc): return [t for t in doc if not t.is_stop] def _lemmatize(self, doc): return ' '.join([t.lemma_ for t in doc]) This code could be used in sklearn pipeline. Measured performance: 2225 texts were processed on 4 processes for 22 minutes. Not even close to being fast! This causes the normalization part, the library is not sufficiently optimized, but produces rather interesting results and can bring additional value for further vectorization, so it is up to you, whether to use it or not. I hope you liked this post and I’m looking forward to your feedback! Kaggle kernel: https://www.kaggle.com/balatmak/text-preprocessing-steps-and-universal-pipeline
[ { "code": null, "e": 737, "s": 172, "text": "Before feeding any ML model some kind data, it has to be properly preprocessed. You must have heard the byword: Garbage in, garbage out (GIGO). Text is a specific kind of data and can't be directly fed to most ML models, so before feeding it to a model yo...
JavaScript | Object.defineProperty() Method - GeeksforGeeks
16 Apr, 2020 The Object.defineProperty() method in JavaScript is a Standard built-in objects which defines a new property directly on an object and returns the object. Syntax: Object.defineProperty(obj, prop, descriptor) Parameter: This method accept three parameters as mentioned above and described below: Obj: This parameter holds the Object on which user is going to be define the property. Prop: This parameter holds the name of a property which is going to be defined or modified. Descriptor: This parameter holds the descriptor for the property being defined or modified. Return Value: This method returns the object which is passed as the argument to the function. Below examples illustrate the Object.defineProperty() method in JavaScript: Example 1: <script>const geek1 = {};Object.defineProperty(geek1, 'prop1', { value: 65, writable: false});geek1.prop1 = 7;console.log(geek1.prop1); const geek2 = {}; Object.defineProperty(geek2, 'prop2', { value: 54, value: 23, value: 12*9, }); geek2.prop2 ; console.log(geek2.prop2); </script> Output: 65 108 Example 2: <script>function gfg() {} var result;Object.defineProperty(gfg.prototype, "valx", { get() { return result; }, set(valx) { result = valx; }}); var vala = new gfg();var valb = new gfg();vala.valx = 6;console.log(valb.valx); function gfg1() {} gfg1.prototype.valx = 4;Object.defineProperty(gfg1.prototype, "valy", { writable: false, value: 8}); var vala = new gfg1();vala.valx = 4;console.log(vala.valx); console.log(gfg1.prototype.valx); vala.valy = 2;console.log(vala.valy);console.log(gfg1.prototype.valy);</script> Output: 6 4 4 8 8 Supported Browsers: The browsers supported by Object.defineProperty() method are listed below: Google Chrome Firefox Opera Safari Edge javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25220, "s": 25192, "text": "\n16 Apr, 2020" }, { "code": null, "e": 25375, "s": 25220, "text": "The Object.defineProperty() method in JavaScript is a Standard built-in objects which defines a new property directly on an object and returns the object." }, ...
Lolcode - Input/Output
This chapter will explain you how to input a value through LOLCODE terminal and how to output it onto the terminal. You can use the keyword VISIBLE to print something in LOLCODE. VISIBLE is a function which can take an infinite number of characters as input, and prints them all at once by internally concatenating them, and converting them to strings or YARN. The VISIBLE function ends or terminates by a delimiter, which is either a line end or a comma. The output is automatically terminated by the compiler with a carriage return. If the final token is terminated with an exclamation symbol (!), then the carriage returned is over-ridden by this symbol. VISIBLE <any_expression> [<any_expression> ...][!] Please note that in LOLCODE, currently there is no defined standard for printing some data to a file. To take some input from the user, the keyword used is GIMMEH. It is a function which can take any number of variables as input. It takes YARN as the input and stores the value in any given variable. GIMMEH <any_variable> HAI 1.2 I HAS A VAR ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE VISIBLE "TYPE SOMETHING AND ENTER" GIMMEH VAR BTW GET INPUT (STRING) INTO VARIABLE VISIBLE VAR KTHXBYE When this code is run, it will ask you to enter a number and then prints the number back in the next line automatically. When you run this code, it will print the following output − sh- 4.3$ lci main.lo TYPE SOMETHING AND ENTER 67 67 Print Add Notes Bookmark this page
[ { "code": null, "e": 1956, "s": 1840, "text": "This chapter will explain you how to input a value through LOLCODE terminal and how to output it onto the terminal." }, { "code": null, "e": 2201, "s": 1956, "text": "You can use the keyword VISIBLE to print something in LOLCODE. VIS...
How to subset a data.table object using a range of values in R?
To subset a data.table object using a range of values, we can use single square brackets and choose the range using %between%. For example, if we have a data.table object DT that contains a column x and the values in x ranges from 1 to 10 then we can subset DT for values between 3 to 8 by using the command DT[DT$x %between% c(3,8)]. Loading data.table package and creating a data.table object − library(data.table) x1<-rnorm(20) x2<-rnorm(20,100,3.25) dt1<-data.table(x1,x2) dt1 x1 x2 1: 0.06546822 102.83348 2: 1.05756760 99.28015 3: 0.09397791 97.36582 4: -0.44478256 96.22510 5: -0.17392089 99.56077 6: 0.32834773 95.85831 7: -0.04563975 104.88298 8: 0.95807930 95.31325 9: 1.25349243 101.72948 10: 0.47676550 96.76459 11: -1.26790256 98.76222 12: -1.36220203 97.91117 13: -1.31999499 102.81730 14: 1.69391374 96.00380 15: -0.10801512 101.69544 16: -1.13463486 108.11833 17: -0.13885823 102.34798 18: -0.54403332 99.68874 19: 0.55865944 97.33505 20: 0.76511431 96.53975 Subsetting rows of dt1 for values 0.5 to 1 of x1 − dt1[dt1$x1 %between% c(0.5,1)] x1 x2 1: 0.9580793 95.31325 2: 0.5586594 97.33505 3: 0.7651143 96.53975 y1<-rpois(20,5) y2<-rpois(20,2) dt2<-data.table(y1,y2) dt2 y1 y2 1: 7 1 2: 3 2 3: 1 5 4: 4 2 5: 5 3 6: 4 1 7: 3 2 8: 5 0 9: 5 2 10: 7 4 11: 5 4 12: 6 2 13: 6 4 14: 6 2 15: 5 2 16: 1 1 17: 3 1 18: 2 4 19: 4 0 20: 4 1 Subsetting rows of dt1 for values 2 to 6 of y2 − dt2[dt2$y2 %between% c(2,6)] y1 y2 1: 3 2 2: 1 5 3: 4 2 4: 5 3 5: 3 2 6: 5 2 7: 7 4 8: 5 4 9: 6 2 10: 6 4 11: 6 2 12: 5 2 13: 2 4
[ { "code": null, "e": 1397, "s": 1062, "text": "To subset a data.table object using a range of values, we can use single square brackets and choose the range using %between%. For example, if we have a data.table object DT that contains a column x and the values in x ranges from 1 to 10 then we can su...
HTML - Overview
HTML stands for Hypertext Markup Language, and it is the most widely used language to write Web Pages. Hypertext refers to the way in which Web pages (HTML documents) are linked together. Thus, the link available on a webpage is called Hypertext. Hypertext refers to the way in which Web pages (HTML documents) are linked together. Thus, the link available on a webpage is called Hypertext. As its name suggests, HTML is a Markup Language which means you use HTML to simply "mark-up" a text document with tags that tell a Web browser how to structure it to display. As its name suggests, HTML is a Markup Language which means you use HTML to simply "mark-up" a text document with tags that tell a Web browser how to structure it to display. Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between researchers. Now, HTML is being widely used to format web pages with the help of different tags available in HTML language. In its simplest form, following is an example of an HTML document − <!DOCTYPE html> <html> <head> <title>This is document title</title> </head> <body> <h1>This is a heading</h1> <p>Document content goes here.....</p> </body> </html> Document content goes here..... As told earlier, HTML is a markup language and makes use of various tags to format the content. These tags are enclosed within angle braces <Tag Name>. Except few tags, most of the tags have their corresponding closing tags. For example, <html> has its closing tag </html> and <body> tag has its closing tag </body> tag etc. Above example of HTML document uses the following tags − This tag defines the document type and HTML version. This tag encloses the complete HTML document and mainly comprises of document header which is represented by <head>...</head> and document body which is represented by <body>...</body> tags. This tag represents the document's header which can keep other HTML tags like <title>, <link> etc. The <title> tag is used inside the <head> tag to mention the document title. This tag represents the document's body which keeps other HTML tags like <h1>, <div>, <p> etc. This tag represents the heading. This tag represents a paragraph. To learn HTML, you will need to study various tags and understand how they behave, while formatting a textual document. Learning HTML is simple as users have to learn the usage of different tags in order to format the text or images to make a beautiful webpage. World Wide Web Consortium (W3C) recommends to use lowercase tags starting from HTML 4. A typical HTML document will have the following structure − <html> <head> Document header related tags </head> <body> Document body related tags </body> </html> We will study all the header and body tags in subsequent chapters, but for now let's see what is document declaration tag. The <!DOCTYPE> declaration tag is used by the web browser to understand the version of the HTML used in the document. Current version of HTML is 5 and it makes use of the following declaration − <!DOCTYPE html> There are many other declaration types which can be used in HTML document depending on what version of HTML is being used. We will see more details on this while discussing <!DOCTYPE...> tag along with other HTML tags. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2477, "s": 2374, "text": "HTML stands for Hypertext Markup Language, and it is the most widely used language to write Web Pages." }, { "code": null, "e": 2621, "s": 2477, "text": "Hypertext refers to the way in which Web pages (HTML documents) are linked toge...
Explore and Visualize a Dataset with Python | by Fabian Bosler | Towards Data Science
In last week’s story, “Extracting data from various sheets with Python” you learned how to retrieve and unify data from different sources (Google Sheets, CSV, and Excel). Both stories work as a standalone story, so don’t worry if you skipped last week’s piece. towardsdatascience.com how to combine and wrangle the data, how to explore and analyze the data, how to create beautiful graphs to visualize your findings People who work with data a lot People who have a basic understanding of Python and Pandas You are tasked with figuring out how to increase your sales team’s performance. In our hypothetical situation, potential customers have rather spontaneous demand. When this happens, your sales team puts an order lead in the system. Your sales reps then try to get set up a meeting that occurs around the time the order lead was noticed. Sometimes before, sometimes after. Your sales reps have an expense budget and always combine the meeting with a meal for which they pay. The sales reps expense their costs and hand the invoices to the accounting team for processing. After the potential customer has decided whether or not they want to go with your offer, your diligent sales reps track whether or not the order lead converted into a sale. For your analysis, you have access to the following three data sources: order_leads (contains all the order leads and conversion info) sales_team (includes companies and responsible sales reps) invoices (provides information on the invoices and participants) The used libraries are quite standard. However, you might have to install seaborn by running the following command in your Notebook. !pip install seaborn You could either download and combine the data as showcased in last week’s piece or download the files from here and load them into your Notebook. It certainly seems like things went downhill in early 2017. After checking with the chief sales officer, it turns out that a competitor entered the market around that time. That’s good to know, but nothing we can do here now. We use an underscore _ as a temporary variable. I would typically do that for disposable variables that I am not going to use again later on.We used pd.DateTimeIndex on order_leads.Date and set the result as the index, this allows us touse pd.Grouped(freq='D') to group our data by day. Alternatively, you could change frequency to W, M, Q or Y (for week, month, quarter, or year)We calculate the mean of “Converted” for every day, which is going to give us the conversion rate for orders on that day.We used .rolling(60) with .mean() to get the 60 days rolling average.We then format the yticklables such that they show a percentage sign. We use an underscore _ as a temporary variable. I would typically do that for disposable variables that I am not going to use again later on. We used pd.DateTimeIndex on order_leads.Date and set the result as the index, this allows us to use pd.Grouped(freq='D') to group our data by day. Alternatively, you could change frequency to W, M, Q or Y (for week, month, quarter, or year) We calculate the mean of “Converted” for every day, which is going to give us the conversion rate for orders on that day. We used .rolling(60) with .mean() to get the 60 days rolling average. We then format the yticklables such that they show a percentage sign. It looks like there is quite some variability across sales reps. Let’s investigate this a little bit more. Not much new here in terms of functionalities being used. But note how we use sns.distplot to plot the data to the axis. If we recall the sales_team data, we remember that not all sales reps have the same number of accounts, this could certainly have an impact! Let’s check. We can see that the conversion rate numbers seem to be decreasing inversely proportional to the number of accounts assigned to a sales rep. Those decreasing conversion rates make sense. After all, the more accounts a rep has, the less time he can spend on each one. Here we first create a helper function that will map the vertical line into each subplot and annotate the line with the mean and standard deviation of the data. We then set some seaborn plotting defaults, like larger font_scale and whitegrid as style. It looks like we’ve got a date and time for the meals, let’s take a quick look at the time distribution: out:07:00:00 553608:00:00 561309:00:00 547312:00:00 561413:00:00 541214:00:00 563320:00:00 552821:00:00 553422:00:00 5647 It looks like we can summarize those: Note how we are using pd.cut here to assign categories to our numeric data, which makes sense because after all, it probably does not matter if a breakfast starts at 8 o’clock or 9 o’clock. Additionally, note how we use .dt.hour, we can only do this because we converted invoices['Date of Meal'] to datetime before. .dt is a so-called accessor, there are three of those cat, str, dt. If your data has the correct type, you can use those accessors and their methods for straightforward manipulation (computationally efficient and concise). invoices['Participants'], unfortunately, is a string we have to convert that first into legitimate JSON so that we can extract the number of participants. Now let’s combine the data. To do this, we first left-join all invoices by Company Id on order_leads. Merging the data, however, leads to all meals joined to all orders. Also ancient meals to more recent orders. To mitigate that we calculate the time difference between meal and order and only consider meals that were five days around the order.There are still some orders that have multiple meals assigned to them. This can happen when there were two orders around the same time and also two meals. Then both meals would get assigned to both order leads. To remove those duplicates, we only keep the meal closest to that order. I created a plot bar function that already includes some styling. The plotting via the function makes visual inspection much faster. We are going to use it in a second. Wow! That is quite a significant difference in conversion rates between orders that had a meal associated with them and the ones without meals. It looks like lunch has a slightly lower conversion rate than dinner or breakfast, though. A negative number for 'Days of meal before order' means that the meal took place after the order lead came in. We can see that there seems to be a positive effect on conversion rate if the meal happens before the order lead comes in. It looks like the prior knowledge of the order is giving our sales reps an advantage here. We’ll use a heatmap to visualize multiple dimensions of the data at the same time now. For this lets first create a helper function. Then we apply some final data wrangling to additionally consider meal price in relation to order value and bucket our lead times into Before Order, Around Order, After Order instead of days from negative four to positive four because that would be somewhat busy to interpret. Running the following snippet will then produce a multi-dimensional heatmap. The heatmap is certainly pretty, although a little hard to read at first. So let’s go over it. The chart summarizes the effect of 4 different dimensions: Timing of the meal: After Order, Around Order, Before Order (outer rows) Type of meal: breakfast, dinner, lunch (outer columns) Meal Price / Order Values: Least Expensive, Less Expensive, Proportional, More Expensive, Most Expensive (inner rows) Number Participants: 1,2,3,4,5 (inner columns) It certainly seems like the colors are darker/higher towards the bottom part of the chart, which indicates that conversion rates are higher when the meal happens before the order It seems like for dinner conversion rates are higher, when there is only one participant It looks like more expensive meals compared to the order value have a positive effect on conversion rate Don’t give your sales reps more than 9 accounts (as conversion rate drops off rapidly)Make sure that every order lead is accompanied by a meeting/meal (as this more than doubles conversion rateDinners are the most effective when there is only one employee from the customerYour sales reps should be paying meals that are roughly 8% to 10% of the order valueTiming is key, ideally, your sales reps know as early as possible that a deal is coming up. Don’t give your sales reps more than 9 accounts (as conversion rate drops off rapidly) Make sure that every order lead is accompanied by a meeting/meal (as this more than doubles conversion rate Dinners are the most effective when there is only one employee from the customer Your sales reps should be paying meals that are roughly 8% to 10% of the order value Timing is key, ideally, your sales reps know as early as possible that a deal is coming up. Click here for the code: GitHub Repo/Jupyter Notebook Remark for the Heatmap: To resolve potentially wonky formatting, you can downgrade matplotlib to version 3.1.0 by uninstalling (you will have to do that in the terminal) first and then running: !pip install matplotlib==3.1.0 Let me know if you are having problems with this
[ { "code": null, "e": 433, "s": 172, "text": "In last week’s story, “Extracting data from various sheets with Python” you learned how to retrieve and unify data from different sources (Google Sheets, CSV, and Excel). Both stories work as a standalone story, so don’t worry if you skipped last week’s p...
How to get the widget name in the event in Tkinter?
Tkinter is a Python library that is used to create and develop functional GUI-based applications. Tkinter provides widgets that can be used for constructing the visual and functional representation of the application. Let us suppose that we have defined some widgets in our application. If we want to get a widget's name in an event, then it can be achieved by using event.widget["text"] keywords inside a function. We can print the name by using it inside the print() function. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the tkinter window win.geometry("700x300") # Define a function to delete the shape def on_click(): print (win.winfo_children()) # Create a canvas widget canvas=Canvas(win, width=500, height=300) canvas.pack() # Create a button to delete the button Button(win, text="Click", command=on_click).pack() win.mainloop() If we run the above code, it will display a window with a button. If we click the button, the output will show the name of the widget on the screen. [<tkinter.Canvas object .!canvas>, <tkinter.Button object .!button>]
[ { "code": null, "e": 1280, "s": 1062, "text": "Tkinter is a Python library that is used to create and develop functional GUI-based applications. Tkinter provides widgets that can be used for constructing the visual and functional representation of the application." }, { "code": null, "e"...
Print nodes in top view of Binary Tree | Set 2 - GeeksforGeeks
24 Jun, 2021 Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of the left child of a node x is equal to the horizontal distance of x minus 1, and that of right child is the horizontal distance of x plus 1. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: Top view: 4 2 1 3 7 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: Top view: 2 1 3 6 The idea is to do something similar to Vertical Order Traversal. Like Vertical Order Traversal, we need to group nodes of same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal node is visited before any other node of same horizontal distance below it. A Map is used to map the horizontal distance of the node with the node’s Data and vertical distance of the node. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to print Top View of Binary Tree// using hashmap and recursion#include <bits/stdc++.h>using namespace std; // Node structurestruct Node { // Data of the node int data; // Horizontal Distance of the node int hd; // Reference to left node struct Node* left; // Reference to right node struct Node* right;}; // Initialising nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->hd = INT_MAX; node->left = NULL; node->right = NULL; return node;} void printTopViewUtil(Node* root, int height, int hd, map<int, pair<int, int> >& m){ // Base Case if (root == NULL) return; // If the node for particular horizontal distance // is not present in the map, add it. // For top view, we consider the first element // at horizontal distance in level order traversal if (m.find(hd) == m.end()) { m[hd] = make_pair(root->data, height); } else{ pair<int, int> p = (m.find(hd))->second; if (p.second > height) { m.erase(hd); m[hd] = make_pair(root->data, height); } } // Recur for left and right subtree printTopViewUtil(root->left, height + 1, hd - 1, m); printTopViewUtil(root->right, height + 1, hd + 1, m);} void printTopView(Node* root){ // Map to store horizontal distance, // height and node's data map<int, pair<int, int> > m; printTopViewUtil(root, 0, 0, m); // Print the node's value stored by printTopViewUtil() for (map<int, pair<int, int> >::iterator it = m.begin(); it != m.end(); it++) { pair<int, int> p = it->second; cout << p.first << " "; }} int main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->left->right->right = newNode(5); root->left->right->right->right = newNode(6); cout << "Top View : "; printTopView(root); return 0;} // Java Program to print Top View of Binary Tree// using hashmap and recursionimport java.util.*; class GFG { // Node structure static class Node { // Data of the node int data; // Reference to left node Node left; // Reference to right node Node right; }; static class pair { int data, height; public pair(int data, int height) { this.data = data; this.height = height; } } // Initialising node static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return node; } static void printTopViewUtil(Node root, int height, int hd, Map<Integer, pair> m) { // Base Case if (root == null) return; // If the node for particular horizontal distance // is not present in the map, add it. // For top view, we consider the first element // at horizontal distance in level order traversal if (!m.containsKey(hd)) { m.put(hd, new pair(root.data, height)); } else { pair p = m.get(hd); if (p.height >= height) { m.put(hd, new pair(root.data, height)); } } // Recur for left and right subtree printTopViewUtil(root.left, height + 1, hd - 1, m); printTopViewUtil(root.right, height + 1, hd + 1, m); } static void printTopView(Node root) { // Map to store horizontal distance, // height and node's data Map<Integer, pair> m = new TreeMap<>(); printTopViewUtil(root, 0, 0, m); // Print the node's value stored by // printTopViewUtil() for (Map.Entry<Integer, pair> it : m.entrySet()) { pair p = it.getValue(); System.out.print(p.data + " "); } } // Driver code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); System.out.print("Top View : "); printTopView(root); }} # Python3 Program to prTop View of# Binary Tree using hash and recursionfrom collections import OrderedDict # A binary tree nodeclass newNode: # A constructor to create a # new Binary tree Node def __init__(self, data): self.data = data self.left = None self.right = None self.hd = 2**32 def printTopViewUtil(root, height, hd, m): # Base Case if (root == None): return # If the node for particular horizontal # distance is not present in the map, add it. # For top view, we consider the first element # at horizontal distance in level order traversal if hd not in m : m[hd] = [root.data, height] else: p = m[hd] if p[1] > height: m[hd] = [root.data, height] # Recur for left and right subtree printTopViewUtil(root.left, height + 1, hd - 1, m) printTopViewUtil(root.right, height + 1, hd + 1, m) def printTopView(root): # to store horizontal distance, # height and node's data m = OrderedDict() printTopViewUtil(root, 0, 0, m) # Print the node's value stored # by printTopViewUtil() for i in sorted(list(m)): p = m[i] print(p[0], end = " ") # Driver Coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.right = newNode(4)root.left.right.right = newNode(5)root.left.right.right.right = newNode(6) print("Top View : ", end = "")printTopView(root) # This code is contributed by SHUBHAMSINGH10 // C# program to print Top View of Binary// Tree using hashmap and recursionusing System;using System.Collections.Generic; class GFG{ // Node structureclass Node{ // Data of the node public int data; // Reference to left node public Node left; // Reference to right node public Node right;}; class pair{ public int data, height; public pair(int data, int height) { this.data = data; this.height = height; }} // Initialising nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} static void printTopViewUtil(Node root, int height, int hd, SortedDictionary<int, pair> m){ // Base Case if (root == null) return; // If the node for particular horizontal distance // is not present in the map, add it. // For top view, we consider the first element // at horizontal distance in level order traversal if (!m.ContainsKey(hd)) { m[hd] = new pair(root.data, height); } else { pair p = m[hd]; if (p.height >= height) { m[hd] = new pair(root.data, height); } } // Recur for left and right subtree printTopViewUtil(root.left, height + 1, hd - 1, m); printTopViewUtil(root.right, height + 1, hd + 1, m);} static void printTopView(Node root){ // Map to store horizontal distance, // height and node's data SortedDictionary<int, pair> m = new SortedDictionary<int, pair>(); printTopViewUtil(root, 0, 0, m); // Print the node's value stored by // printTopViewUtil() foreach(var it in m.Values) { Console.Write(it.data + " "); }} // Driver codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); Console.Write("Top View : "); printTopView(root);}} // This code is contributed by rutvik_56 <script> // JavaScript program to print Top View of Binary// Tree using hashmap and recursion // Node structureclass Node{ constructor() { // Data of the node this.data = 0; // Reference to left node this.left = null; // Reference to right node this.right = null; }}; class pair{ constructor(data, height) { this.data = data; this.height = height; }} // Initialising nodefunction newNode(data){ var node = new Node(); node.data = data; node.left = null; node.right = null; return node;} function printTopViewUtil(root, height, hd, m){ // Base Case if (root == null) return; // If the node for particular horizontal distance // is not present in the map, add it. // For top view, we consider the first element // at horizontal distance in level order traversal if (!m.has(hd)) { m.set(hd, new pair(root.data, height)); } else { var p = m.get(hd); if (p.height >= height) { m.set(hd, new pair(root.data, height)); } } // Recur for left and right subtree printTopViewUtil(root.left, height + 1, hd - 1, m); printTopViewUtil(root.right, height + 1, hd + 1, m);} function printTopView(root){ // Map to store horizontal distance, // height and node's data var m = new Map(); printTopViewUtil(root, 0, 0, m); // Print the node's value stored by // printTopViewUtil() for(var it of [...m].sort()) { document.write(it[1].data + " "); }} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.right = newNode(4);root.left.right.right = newNode(5);root.left.right.right.right = newNode(6);document.write("Top View : ");printTopView(root); </script> Top View : 2 1 3 6 SHUBHAMSINGH10 Rajput-Ji sumantataken Aman yadav 5 rutvik_56 noob2000 Binary Tree cpp-map Hash Tree Traversals tree-level-order tree-view Tree Hash Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Introduction to Tree Data Structure Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Expression Tree Lowest Common Ancestor in a Binary Tree | Set 1
[ { "code": null, "e": 25316, "s": 25288, "text": "\n24 Jun, 2021" }, { "code": null, "e": 25511, "s": 25316, "text": "Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should ...
F# - Mutable Data
Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties. The following example demonstrates this. let x = 10 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z let x = 15 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z When you compile and execute the program, it shows the following error message − Duplicate definition of value 'x' Duplicate definition of value 'Y' Duplicate definition of value 'Z' At times you need to change the values stored in a variable. To specify that there could be a change in the value of a declared and assigned variable in later part of a program, F# provides the mutable keyword. You can declare and assign mutable variables using this keyword, whose values you will change. The mutable keyword allows you to declare and assign values in a mutable variable. You can assign some initial value to a mutable variable using the let keyword. However, to assign new subsequent value to it, you need to use the <- operator. For example, let mutable x = 10 x <- 15 The following example will clear the concept − let mutable x = 10 let y = 20 let mutable z = x + y printfn "Original Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z printfn "Let us change the value of x" printfn "Value of z will change too." x <- 15 z <- x + y printfn "New Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z When you compile and execute the program, it yields the following output − Original Values: x: 10 y: 20 z: 30 Let us change the value of x Value of z will change too. New Values: x: 15 y: 20 z: 35 Mutable data is often required and used in data processing, particularly with record data structure. The following example demonstrates this − open System type studentData = { ID : int; mutable IsRegistered : bool; mutable RegisteredText : string; } let getStudent id = { ID = id; IsRegistered = false; RegisteredText = null; } let registerStudents (students : studentData list) = students |> List.iter(fun st -> st.IsRegistered <- true st.RegisteredText <- sprintf "Registered %s" (DateTime.Now.ToString("hh:mm:ss")) Threading.Thread.Sleep(1000) (* Putting thread to sleep for 1 second to simulate processing overhead. *)) let printData (students : studentData list) = students |> List.iter (fun x -> printfn "%A" x) let main() = let students = List.init 3 getStudent printfn "Before Process:" printData students printfn "After process:" registerStudents students printData students Console.ReadKey(true) |> ignore main() When you compile and execute the program, it yields the following output − Before Process: {ID = 0; IsRegistered = false; RegisteredText = null;} {ID = 1; IsRegistered = false; RegisteredText = null;} {ID = 2; IsRegistered = false; RegisteredText = null;} After process: {ID = 0; IsRegistered = true; RegisteredText = "Registered 05:39:15";} {ID = 1; IsRegistered = true; RegisteredText = "Registered 05:39:16";} {ID = 2; IsRegistered = true; RegisteredText = "Registered 05:39:17";} Print Add Notes Bookmark this page
[ { "code": null, "e": 2321, "s": 2161, "text": "Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties." }, { "code": null, "e": 2362, "s": 2321, "text": "The following example ...
Denial of Service and Prevention - GeeksforGeeks
02 Nov, 2021 Denial of Service (DoS) is a cyber-attack on an individual Computer or Website with the intent to deny services to intended users. Their purpose is to disrupt an organization’s network operations by denying access to its users. Denial of service is typically accomplished by flooding the targeted machine or resource with surplus requests in an attempt to overload systems and prevent some or all legitimate requests from being fulfilled.For example, if a bank website can handle 10 people a second clicking the Login button, an attacker only has to send 10 fake requests per second to make it so no legitimate users can login. DoS attacks exploit various weaknesses in computer network technologies. They may target servers, network routers, or network communication links. They can cause computers and routers to crash and links to bog down. The most famous DoS technique is Ping of Death. The Ping of Death attack works by generating and sending special network messages (specifically, ICMP packets of non-standard sizes) that cause problems for systems that receive them. In the early days of the Web, this attack could cause unprotected Internet servers to crash quickly. It is strongly recommended to try all described activities on virtual machines rather than your working environment Following is the command for performing flooding of requests on an IP ping ip_address –t -65500 HERE, “ping” sends the data packets to the victim. “ip_address” is the IP address of the victim. “-t” means the data packets should be sent until the program is stopped. “-l(65500)” specifies the data load to be sent to the victim. Other basic types of DoS attacks involve Flooding a network with useless activity so that genuine traffic cannot get through. The TCP/IP SYN and smurf attacks are two common examples. Remotely overloading a system’s CPU so that valid requests cannot be processed. Changing permissions or breaking authorization logic to prevent users from logging into a system. One common example involves triggering a rapid series of false login attempts that lockout accounts from being able to log in. Deleting or interfering with specific critical applications or services to prevent their normal operation (even if the system and network overall are functional). Another variant of the DoS is the Smurf_attack. This involves emails with automatic responses. If someone emails hundreds of email messages with a fake return email address to hundreds of people in an organization with an autoresponder on in their email, the initial sent messages can become thousands sent to the fake email address. If that fake email address actually belongs to someone, this can overwhelm that person’s account. DoS attacks can cause the following problems: Ineffective services Inaccessible services Interruption of network traffic Connection interference Following is the python script for performing a denial of service attack for a small website that didn’t expect so much socket connection # Please note that running this code might# cause your IP blocked by server. And purpose# of this code is only learning.import socket, sys, os print "][ Attacking " + sys.argv[1] + " ... ][" print "injecting " + sys.argv[2]; def attack(): #pid = os.fork() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((sys.argv[1], 80)) print ">> GET /" + sys.argv[2] + " HTTP/1.1" s.send("GET /" + sys.argv[2] + " HTTP/1.1\r\n") s.send("Host: " + sys.argv[1] + "\r\n\r\n"); s.close() # Driver codefor i in range(1, 1000): attack() We can use above code as python ddos.py target_ip_address apache Prevention Given that Denial of Service (DoS) attacks are becoming more frequent, it is a good time to review the basics and how we can fight back. Cloud Mitigation Provider – Cloud mitigation providers are experts at providing DDoS mitigation from the cloud. This means they have built out massive amounts of network bandwidth and DDoS mitigation capacity at multiple sites around the Internet that can take in any type of network traffic, whether you use multiple ISP’s, your own data center, or any number of cloud providers. They can scrub the traffic for you and only send “clean” traffic to your data center. Firewall – This is the simplest and least effective method. Generally, someone writes some Python scripts that try to filter out the bad traffic or an enterprise will try and use its existing firewalls to block the traffic Internet Service Provider (ISP) – Some enterprises use their ISP to provide DDoS mitigation. These ISP’s have more bandwidth than an enterprise would, which can help with the large volumetric attacks To safeguard from these attacks you have to apply secure coding and design strong architecture which can prevent these kinds of attacks and update day-to-day solutions to bugs on your website. Referenceshttps://www.owasp.org/index.php/Denial_of_Servicehttps://en.wikipedia.org/wiki/Denial-of-service_attack This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nerdynikhil vaibhavsinghtanwar3 secure-coding Advanced Computer Subject Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Naive Bayes Classifiers Linear Regression (Python Implementation) Apriori Algorithm Removing stop words with NLTK in Python Decision Tree Caesar Cipher in Cryptography UDP Server-Client implementation in C Socket Programming in Python Differences between IPv4 and IPv6 Advanced Encryption Standard (AES)
[ { "code": null, "e": 36514, "s": 36486, "text": "\n02 Nov, 2021" }, { "code": null, "e": 37142, "s": 36514, "text": "Denial of Service (DoS) is a cyber-attack on an individual Computer or Website with the intent to deny services to intended users. Their purpose is to disrupt an o...
How does * operator work on list in Python?
The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, you could just use the * operator. def multiply(a, b): return a * b values = [1, 2] print(multiply(*values)) This will unpack the list so that it actually executes as − print(multiply(1, 2)) This will give the output − 2
[ { "code": null, "e": 1349, "s": 1062, "text": "The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, yo...
How to calculate initial cash flows?
The solution is mentioned below − Fixed capital = $ 2000 Working capital = $ 200 Salvage value = $ 1600 Book value = $ 1200 Tax rate = 28% Initial cash flows = FC+WC-S + (S-B) * T = 2000 + 200 – 1600 + (1600 – 1200) * 0.28 = 2000 + 200 – 1600 + 112 = 2312 – 1600 = = $712 Here FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate A toy manufacturer company had following data New equipment cost = 700000Salvagevalue= 475000 Additional expenses = 17500Bookvalue= 390000 Tax rate = 18% Calculate initial cash flow A toy manufacturer company had following data New equipment cost = 700000Salvagevalue= 475000 Additional expenses = 17500Bookvalue= 390000 Tax rate = 18% Calculate initial cash flow The solution is explained below − Initial cash flows = FC+WC-S + (S-B) * T = 700000 + 17500 – 475000 + (475000 – 390000) * 0.18 = 700000 + 17500 – 475000 + 15300 = 732800 – 4750000 = $257800 Here FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate
[ { "code": null, "e": 1096, "s": 1062, "text": "The solution is mentioned below −" }, { "code": null, "e": 1201, "s": 1096, "text": "Fixed capital = $ 2000\nWorking capital = $ 200\nSalvage value = $ 1600\nBook value = $ 1200\nTax rate = 28%" }, { "code": null, "e": 12...
Simple Portfolio Website Design using HTML
08 Aug, 2021 Being a web developer and having a portfolio helps a lot while applying for opportunities and acts as a showcase of our talent, so in this article, we will learn how to make a simple one-page portfolio by just using HTML. This portfolio might contain some very important information of yours like: about us section your projects your achievements your contact details You can even add other details too in your portfolio and can make it more beautiful. But this article focuses on beginners who are wanting to learn to build their portfolio using simple HTML. Prerequisite: Basic concepts of HTML like tags, attributes ,forms, tables, rows, columns, hyperlink etc. Code Implementation: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>HTML Project</title></head> <body> <!--Header(start)--> <table id="header" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#4CAF50"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="90%" align="center"> <tr> <td> </td> <td> <font face="Comic sans MS" size="6"> <b>GeeksForGeeks</b> </font> </td> <td width="15%"> </td> <td> <a href="#home" style="text-decoration:none"> <font face="Verdana" size="5" color=black> Home </font> </a> </td> <td> | </td> <td> <a href="#about" style="text-decoration:none"> <font face="Verdana" size="5" color=black> About </font> </a> </td> <td> | </td> <td> <a href="#projects" style="text-decoration:none"> <font face="Verdana" size="5" color=black> Projects </font> </a> </td> <td> | </td> <td> <a href="#achievements" style="text-decoration:none"> <font face="Verdana" size="5" color=black> Achievements </font> </a> </td> <td> | </td> <td> <a href="#contact" style="text-decoration:none"> <font face="Verdana" size="5" color=black> Contact </font> </a> </td> </tr> </table> </td> </tr> </table> <!--Header(end)--> <!--Home(start)--> <table id="home" border="1" width="100%" cellpadding="20" cellspacing="0" bgcolor="black"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="90%" align="center"> <tr> <td align="center" valign="middle"> <h3> <font face="Times New Roman" size="6" color="#ffffff"> Hi Geeks! </font> </h3> <h2> <font face="Verdana" size="6" color="#4CAF50"> <!-- Freelance Programmer --> </font> </h2> </td> </tr> </table> </td> </tr> </table> <!--Home(end)--> <!--About(start)--> <table id="about" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="black"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="80%" align="center"> <tr> <td height="180" align="center" valign="middle" colspan="2"> <font face="Verdana" size="7" color="#4CAF50"> About Me </font> <hr color="#4CAF50" width="90"> </td> </tr> <tr> <td width="40%"> <img src="img.png"> </td> <td width="60%"> <font face="Verdana" size="4" color="white"> Thanks for your interest, here is a quick story of me and this website. <hr color="black"> Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. <hr color="black"> I do my work mainly in C-Language, C++ and JAVA. C++ and Data Structure & Algorithm are my stronger section. Besides these I know Web Development, LINUX and database as well. <hr color="black"> This website is basically one of my Web Development project which is built using HTML only. Here one can also find ideas for projects in different languages. Thanks again for reading this, because of people like you, it exists and prospers! <hr color="black"> Cheers, <br> <b>GeeksForGeeks.</b> </font> </td> </tr> </table> <hr color="black"> <hr color="black"> <hr color="black"> </td> </tr> </table> <!--About(end)--> <!--Projects(start)--> <table id="projects" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#c2c0c3"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="80%" align="center"> <tr> <td height="180" align="center" valign="middle" colspan="2"> <font face="Verdana" size="7" color="black"> Projects </font> <hr color="black" width="90"> </td> </tr> <tr> <td height="10"> <font face="Times New Roman" size="5" color="black"> <ul> <li> BMI Calculator <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Calculator <a href="#" style="text-decoration:none" color="#c2c0c3"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Calendar <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> ChatBot <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Contact Saver <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Daily Quiz <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Emplyoyee Record System <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Guess the Number-Game <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Random Password Generator <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Stone Paper Scissor <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Tic Tac Toe <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Tic Tac Toe(GUI) <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> ToDo App <a href="#" style="text-decoration:none"> ➲ </a> </li> <li> <hr color="#c2c0c3"> Travel Management System <a href="#" style= "text-decoration:none"> ➲ </a> </li> </ul> <hr color="#c2c0c3"> <hr color="#c2c0c3"> <hr color="#c2c0c3"> <hr color="#c2c0c3"> </font> </td> <td width="45%"> <img src="img.png" alt="Project" width="75%"> </td> </tr> </table> </td> </tr> </table> <!--Projects(end)--> <!--Achievement(start)--> <table id="achievements" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="black"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="80%" align="center"> <tr> <td height="180" align="center" valign="middle"> <font face="Verdana" size="7" color="#4CAF50"> Achievements <hr color="#4CAF50" width="100"> </font> </td> </tr> <tr> <td> <font face="Verdana" size="4" color="white"> <ul> <li> <b>Intern at GeeksforGeeks.</b> <ul> <li> December,2020 - Present. </li> <li> Write technical articles on programming related topics. </li> </ul> </li> <li> <hr color="black"> <hr color="black"> <hr color="black"> <b>Microsoft Learn Student Ambassador.</b> <ul> <li> August,2020 - Present. </li> <li> Conducted events and workshops on different technologies. </li> </ul> </li> <li> <hr color="black"> <hr color="black"> <hr color="black"> <b>Mentored HackTX.</b> <ul> <li> October,2020. </li> <li> Selected from Microsoft as Student ambassador where I mentored students in their projects. </li> <hr color="black"> <hr color="black"> <hr color="black"> <hr color="black"> <hr color="black"> </ul> </li> </ul> </font> </td> </tr> </table> </td> </tr> </table> <!--Achievement(end)--> <!--Contact(start)--> <table id="contact" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#c2c0c3"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="80%" align="center"> <tr> <td height="180" align="center" valign="middle" colspan="2"> <font face="Verdana" size="7" color="black"> Contact </font> <hr color="black" width="90"> </td> </tr> <tr> <td align="center" valign="top"> <table border="0" width="50%" cellpadding="15" cellspacing="0" align="center" bgcolor="black"> <tr> <td width="30%"> <hr color="black"> <font face="Verdana" size="4" color="#ffffff"> Name </font> </td> <td width="70%"> <font face="Verdana" size="4" color="#ffffff"> <input type="text" size="40"> </font> </td> </tr> <tr> <td width="30%"> <font face="Verdana" size="4" color="#ffffff"> Email </font> </td> <td width="70%"> <font face="Verdana" size="4" color="#ffffff"> <input type="email" size="40"> </font> </td> </tr> <tr> <td width="30%"> <font face="Verdana" size="4" color="#ffffff"> Number </font> </td> <td width="70%"> <font face="Verdana" size="4" color="#ffffff"> <input type="number" size="12"> </font> </td> </tr> <tr> <td width="30%"> <font face="Verdana" size="4" color="#ffffff"> Message </font> </td> <td width="70%"> <font face="Verdana" size="4" color="#ffffff"> <textarea rows="5" cols="37"> </textarea> </font> </td> </tr> <tr> <td width="30%"> </td> <td width="70%"> <button type="Submit"> <font face="Verdana" size="4" color="black"> <b>Submit</b> </font> </button> <hr color="black"> <hr color="black"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </td> </tr> </table> <!--Contact(end)--> <!--Footer1(start)--> <table id="footer" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#4CAF50"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="90%" align="center"> <tr> <td width="13%" valign="top"> <b>LinkedIn</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>GitHub</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>HackerRank</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>GeeksforGeeks</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>Twitter</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>Instagram</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>Email</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> <td> | </td> <td width="13%" valign="top"> <b>Website</b> <a href="#" style="text-decoration:none"> ➲ </a> </td> </tr> </table> </td> </tr> </table> <!--Footer1(end)--> <!--Footer2(start)--> <table id="footer" border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="black"> <tr> <td> <table border="0" cellpadding="15" cellspacing="0" width="90%" align="center"> <tr> <td width="80%" valign="top"> <font face="Verdana" color="#4CAF50" size="5"> ©Copyright 2050 by nobody. All rights reserved. </font> </td> <td width="10%"> <font face="arial" color="black" size="5"> <a href="#header" style="text-decoration:none"> <font face="Verdana" color="#4CAF50" size="6"> <b>TOP </b> </font> </a> </font> </td> </tr> </table> </td> </tr> </table> <!--Footer2(end)--> </body> </html> Note: We have used two photographs as well. One in the about table and other in the project section. Outputs: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari anikaseth98 ysachin2314 HTML-Questions Technical Scripter 2020 HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Aug, 2021" }, { "code": null, "e": 352, "s": 54, "text": "Being a web developer and having a portfolio helps a lot while applying for opportunities and acts as a showcase of our talent, so in this article, we will learn how to make ...
Queue.Clone() Method in C#
15 Feb, 2019 This method is used to create a shallow copy of the Queue. It just creates a copy of the Queue. The copy will have a reference to a clone of the internal elements but not a reference to the original elements. Syntax: public virtual object Clone (); Return Value: The method returns an Object which is just the shallow copy of the Queue. Example 1: Let’s see an example without using a Clone() method and directly copying a Queue using assignment operator ‘=’. In the below code, we can see even if we Dequeue() elements from myQueue2, contents of myQueue is also changed. This is because ‘=’ just assigns the reference of myQueue to myQueue2 and does not create any new Queue. But Clone() creates a new Queue. // C# program to Copy a Queue using // the assignment operatorusing System;using System.Collections; class GFG { // Main Method public static void Main(string[] args) { Queue myQueue = new Queue(); myQueue.Enqueue("Geeks"); myQueue.Enqueue("Class"); myQueue.Enqueue("Noida"); myQueue.Enqueue("UP"); // Creating a copy using the // assignment operator. Queue myQueue2 = myQueue; myQueue2.Dequeue(); PrintValues(myQueue); } public static void PrintValues(IEnumerable myCollection) { // This method prints all the // elements in the Stack. foreach(Object obj in myCollection) Console.WriteLine(obj); }} Class Noida UP Example 2: Here myQueue is unchanged. // C# program to illustrate the use // of Object.Clone() Method using System;using System.Collections; class GFG { // Main Method public static void Main(string[] args) { Queue myQueue = new Queue(); myQueue.Enqueue("Geeks"); myQueue.Enqueue("Class"); myQueue.Enqueue("Noida"); myQueue.Enqueue("UP"); // Creating copy using Clone() method. Queue myQueue2 = (Queue)myQueue.Clone(); myQueue2.Dequeue(); PrintValues(myQueue); } public static void PrintValues(IEnumerable myCollection) { // This method prints all the // elements in the Stack. foreach(Object obj in myCollection) Console.WriteLine(obj); Console.WriteLine(); }} Geeks Class Noida UP Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.clone?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Queue CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# Dictionary with examples C# | How to check whether a List contains a specified element C# | Arrays of Strings C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2019" }, { "code": null, "e": 237, "s": 28, "text": "This method is used to create a shallow copy of the Queue. It just creates a copy of the Queue. The copy will have a reference to a clone of the internal elements but not a re...