title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How do I exclude a specific record in MySQL? | You can exclude a specific record in SQL using not equal to operator(!=). Let us first create a table−
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ClientName varchar(20),
ClientCountryName varchar(10)
);
Query OK, 0 rows affected (0.64 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(ClientName,ClientCountryName) values('John','US');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(ClientName,ClientCountryName) values('David','AUS');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(ClientName,ClientCountryName) values('Mike','UK');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+------------+-------------------+
| Id | ClientName | ClientCountryName |
+----+------------+-------------------+
| 1 | John | US |
| 2 | David | AUS |
| 3 | Mike | UK |
+----+------------+-------------------+
3 rows in set (0.00 sec)
Following is the query to exclude a specific record in MySQL i.e. we are excluding records with ClientName David' or ClientCountryName ='AUS'−
mysql> select *from DemoTable where ClientName!='David' or ClientCountryName!='AUS';
This will produce the following output−
+----+------------+-------------------+
| Id | ClientName | ClientCountryName |
+----+------------+-------------------+
| 1 | John | US |
| 3 | Mike | UK |
+----+------------+-------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "You can exclude a specific record in SQL using not equal to operator(!=). Let us first create a table−"
},
{
"code": null,
"e": 1350,
"s": 1165,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientName varchar(20),\n ClientCountryName varchar(10)\n );\nQuery OK, 0 rows affected (0.64 sec)"
},
{
"code": null,
"e": 1401,
"s": 1350,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1751,
"s": 1401,
"text": "mysql> insert into DemoTable(ClientName,ClientCountryName) values('John','US');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(ClientName,ClientCountryName) values('David','AUS');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable(ClientName,ClientCountryName) values('Mike','UK');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1811,
"s": 1751,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1842,
"s": 1811,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1883,
"s": 1842,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2188,
"s": 1883,
"text": "+----+------------+-------------------+\n| Id | ClientName | ClientCountryName |\n+----+------------+-------------------+\n| 1 | John | US |\n| 2 | David | AUS |\n| 3 | Mike | UK |\n+----+------------+-------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2331,
"s": 2188,
"text": "Following is the query to exclude a specific record in MySQL i.e. we are excluding records with ClientName David' or ClientCountryName ='AUS'−"
},
{
"code": null,
"e": 2416,
"s": 2331,
"text": "mysql> select *from DemoTable where ClientName!='David' or ClientCountryName!='AUS';"
},
{
"code": null,
"e": 2456,
"s": 2416,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 2721,
"s": 2456,
"text": "+----+------------+-------------------+\n| Id | ClientName | ClientCountryName |\n+----+------------+-------------------+\n| 1 | John | US |\n| 3 | Mike | UK |\n+----+------------+-------------------+\n2 rows in set (0.00 sec)"
}
]
|
Transfer Learning with Convolutional Neural Networks in PyTorch | by Will Koehrsen | Towards Data Science | Although Keras is a great library with a simple API for building neural networks, the recent excitement about PyTorch finally got me interested in exploring this library. While I’m one to blindly follow the hype, the adoption by researchers and inclusion in the fast.ai library convinced me there must be something behind this new entry in deep learning.
Since the best way to learn a new technology is by using it to solve a problem, my efforts to learn PyTorch started out with a simple project: use a pre-trained convolutional neural network for an object recognition task. In this article, we’ll see how to use PyTorch to accomplish this goal, along the way, learning a little about the library and about the important concept of transfer learning.
While PyTorch might not be for everyone, at this point it’s impossible to say which deep learning library will come out on top, and being able to quickly learn and use different tools is crucial to succeed as a data scientist.
The complete code for this project is available as a Jupyter Notebook on GitHub. This project was born out of my participation in the Udacity PyTorch scholarship challenge.
Our task will be to train a convolutional neural network (CNN) that can identify objects in images. We’ll be using the Caltech 101 dataset which has images in 101 categories. Most categories only have 50 images which typically isn’t enough for a neural network to learn to high accuracy. Therefore, instead of building and training a CNN from scratch, we’ll use a pre-built and pre-trained model applying transfer learning.
The basic premise of transfer learning is simple: take a model trained on a large dataset and transfer its knowledge to a smaller dataset. For object recognition with a CNN, we freeze the early convolutional layers of the network and only train the last few layers which make a prediction. The idea is the convolutional layers extract general, low-level features that are applicable across images — such as edges, patterns, gradients — and the later layers identify specific features within an image such as eyes or wheels.
Thus, we can use a network trained on unrelated categories in a massive dataset (usually Imagenet) and apply it to our own problem because there are universal, low-level features shared between images. The images in the Caltech 101 dataset are very similar to those in the Imagenet dataset and the knowledge a model learns on Imagenet should easily transfer to this task.
Following is the general outline for transfer learning for object recognition:
Load in a pre-trained CNN model trained on a large datasetFreeze parameters (weights) in model’s lower convolutional layersAdd custom classifier with several layers of trainable parameters to modelTrain classifier layers on training data available for taskFine-tune hyperparameters and unfreeze more layers as needed
Load in a pre-trained CNN model trained on a large dataset
Freeze parameters (weights) in model’s lower convolutional layers
Add custom classifier with several layers of trainable parameters to model
Train classifier layers on training data available for task
Fine-tune hyperparameters and unfreeze more layers as needed
This approach has proven successful for a wide range of domains. It’s a great tool to have in your arsenal and generally the first approach that should be tried when confronted with a new image recognition problem.
With all data science problems, formatting the data correctly will determine the success or failure of the project. Fortunately, the Caltech 101 dataset images are clean and stored in the correct format. If we correctly set up the data directories, PyTorch makes it simple to associate the correct labels with each class. I separated the data into training, validation, and testing sets with a 50%, 25%, 25% split and then structured the directories as follows:
/datadir /train /class1 /class2 . . /valid /class1 /class2 . . /test /class1 /class2 . .
The number of training images by classes is below (I use the terms classes and categories interchangeably):
We expect the model to do better on classes with more examples because it can better learn to map features to labels. To deal with the limited number of training examples we’ll use data augmentation during training (more later).
As another bit of data exploration, we can also look at the size distribution.
Imagenet models need an input size of 224 x 224 so one of the preprocessing steps will be to resize the images. Preprocessing is also where we will implement data augmentation for our training data.
The idea of data augmentation is to artificially increase the number of training images our model sees by applying random transformations to the images. For example, we can randomly rotate or crop the images or flip them horizontally. We want our model to distinguish the objects regardless of orientation and data augmentation can also make a model invariant to transformations of the input data.
An elephant is still an elephant no matter which way it’s facing!
Augmentation is generally only done during training (although test time augmentation is possible in the fast.ai library). Each epoch — one iteration through all the training images — a different random transformation is applied to each training image. This means that if we iterate through the data 20 times, our model will see 20 slightly different versions of each image. The overall result should be a model that learns the objects themselves and not how they are presented or artifacts in the image.
This is the most important step of working with image data. During image preprocessing, we simultaneously prepare the images for our network and apply data augmentation to the training set. Each model will have different input requirements, but if we read through what Imagenet requires, we figure out that our images need to be 224x224 and normalized to a range.
To process an image in PyTorch, we use transforms , simple operations applied to arrays. The validation (and testing) transforms are as follows:
Resize
Center crop to 224 x 224
Convert to a tensor
Normalize with mean and standard deviation
The end result of passing through these transforms are tensors that can go into our network. The training transformations are similar but with the addition of random augmentations.
First up, we define the training and validation transformations:
Then, we create datasets and DataLoaders . By using datasets.ImageFolder to make a dataset, PyTorch will automatically associate images with the correct labels provided our directory is set up as above. The datasets are then passed to a DataLoader , an iterator that yield batches of images and labels.
We can see the iterative behavior of the DataLoader using the following:
# Iterate through the dataloader oncetrainiter = iter(dataloaders['train'])features, labels = next(trainiter)features.shape, labels.shape(torch.Size([128, 3, 224, 224]), torch.Size([128]))
The shape of a batch is (batch_size, color_channels, height, width). During training, validation, and eventually testing, we’ll iterate through the DataLoaders, with one pass through the complete dataset comprising one epoch. Every epoch, the training DataLoader will apply a slightly different random transformation to the images for training data augmentation.
With our data in shape, we next turn our attention to the model. For this, we’ll use a pre-trained convolutional neural network. PyTorch has a number of models that have already been trained on millions of images from 1000 classes in Imagenet. The complete list of models can be seen here. The performance of these models on Imagenet is shown below:
For this implementation, we’ll be using the VGG-16. Although it didn’t record the lowest error, I found it worked well for the task and was quicker to train than other models. The process to use a pre-trained model is well-established:
Load in pre-trained weights from a network trained on a large datasetFreeze all the weights in the lower (convolutional) layers: the layers to freeze are adjusted depending on similarity of new task to original datasetReplace the upper layers of the network with a custom classifier: the number of outputs must be set equal to the number of classesTrain only the custom classifier layers for the task thereby optimizing the model for smaller dataset
Load in pre-trained weights from a network trained on a large dataset
Freeze all the weights in the lower (convolutional) layers: the layers to freeze are adjusted depending on similarity of new task to original dataset
Replace the upper layers of the network with a custom classifier: the number of outputs must be set equal to the number of classes
Train only the custom classifier layers for the task thereby optimizing the model for smaller dataset
Loading in a pre-trained model in PyTorch is simple:
from torchvision import modelsmodel = model.vgg16(pretrained=True)
This model has over 130 million parameters, but we’ll train only the very last few fully-connected layers. Initially, we freeze all of the model’s weights:
# Freeze model weightsfor param in model.parameters(): param.requires_grad = False
Then, we add on our own custom classifier with the following layers:
Fully connected with ReLU activation, shape = (n_inputs, 256)
Dropout with 40% chance of dropping
Fully connected with log softmax output, shape = (256, n_classes)
import torch.nn as nn# Add on classifiermodel.classifier[6] = nn.Sequential( nn.Linear(n_inputs, 256), nn.ReLU(), nn.Dropout(0.4), nn.Linear(256, n_classes), nn.LogSoftmax(dim=1))
When the extra layers are added to the model, they are set to trainable by default ( require_grad=True ). For the VGG-16, we’re only changing the very last original fully-connected layer. All of the weights in the convolutional layers and the the first 5 fully-connected layers are not trainable.
# Only training classifier[6]model.classifierSequential( (0): Linear(in_features=25088, out_features=4096, bias=True) (1): ReLU(inplace) (2): Dropout(p=0.5) (3): Linear(in_features=4096, out_features=4096, bias=True) (4): ReLU(inplace) (5): Dropout(p=0.5) (6): Sequential( (0): Linear(in_features=4096, out_features=256, bias=True) (1): ReLU() (2): Dropout(p=0.4) (3): Linear(in_features=256, out_features=100, bias=True) (4): LogSoftmax() ))
The final outputs from the network are log probabilities for each of the 100 classes in our dataset. The model has a total of 135 million parameters, of which just over 1 million will be trained.
# Find total parameters and trainable parameterstotal_params = sum(p.numel() for p in model.parameters())print(f'{total_params:,} total parameters.')total_trainable_params = sum( p.numel() for p in model.parameters() if p.requires_grad)print(f'{total_trainable_params:,} training parameters.')135,335,076 total parameters.1,074,532 training parameters.
One of the best aspects of PyTorch is the ease of moving different parts of a model to one or more gpus so you can make full use of your hardware. Since I’m using 2 gpus for training, I first move the model to cuda and then create a DataParallel model distributed over the gpus:
# Move to gpumodel = model.to('cuda')# Distribute across 2 gpusmodel = nn.DataParallel(model)
(This notebook should be run on a gpu to complete in a reasonable amount of time. The speedup over a cpu can easily by 10x or more.)
The training loss (the error or difference between predictions and true values) is the negative log likelihood (NLL). (The NLL loss in PyTorch expects log probabilities, so we pass in the raw output from the model’s final layer.) PyTorch uses automatic differentiation which means that tensors keep track of not only their value, but also every operation (multiply, addition, activation, etc.) which contributes to the value. This means we can compute the gradient for any tensor in the network with respect to any prior tensor.
What this means in practice is that the loss tracks not only the error, but also the contribution to the error by each weight and bias in the model. After we calculate the loss, we can then find the gradients of the loss with respect to each model parameter, a process known as backpropagation. Once we have the gradients, we use them to update the parameters with the optimizer. (If this doesn’t sink in at first, don’t worry, it takes a little while to grasp! This powerpoint helps to clarify some points.)
The optimizer is Adam, an efficient variant of gradient descent that generally does not require hand-tuning the learning rate. During training, the optimizer uses the gradients of the loss to try and reduce the error (“optimize”) of the model output by adjusting the parameters. Only the parameters we added in the custom classifier will be optimized.
The loss and optimizer are initialized as follows:
from torch import optim# Loss and optimizercriteration = nn.NLLLoss()optimizer = optim.Adam(model.parameters())
With the pre-trained model, the custom classifier, the loss, the optimizer, and most importantly, the data, we’re ready for training.
Model training in PyTorch is a little more hands-on than in Keras because we have to do the backpropagation and parameter update step ourselves. The main loop iterates over a number of epochs and on each epoch we iterate through the train DataLoader . The DataLoader yields one batch of data and targets which we pass through the model. After each training batch, we calculate the loss, backpropagate the gradients of the loss with respect to the model parameters, and then update the parameters with the optimizer.
I’d encourage you to look at the notebook for the complete training details, but the basic pseudo-code is as follows:
We can continue to iterate through the data until we reach a given number of epochs. However, one problem with this approach is that our model will eventually start overfitting to the training data. To prevent this, we use our validation data and early stopping.
Early stopping means halting training when the validation loss has not decreased for a number of epochs. As we continue training, the training loss will only decrease, but the validation loss will eventually reach a minimum and plateau or start to increase. We ideally want to stop training when the validation loss is at a minimum in the hope that this model will generalize best to the testing data. When using early stopping, every epoch in which the validation loss decreases, we save the parameters so we can later retrieve those with the best validation performance.
We implement early stopping by iterating through the validation DataLoader at the end of each training epoch. We calculate the validation loss and compare this to the lowest validation loss. If the loss is the lowest so far, we save the model. If the loss has not improved for a certain number of epochs, we halt training and return the best model which has been saved to disk.
Again, the complete code is in the notebook, but pseudo-code is:
To see the benefits of early stopping, we can look at the training curves showing the training and validation losses and accuracy:
As expected, the training loss only continues to decrease with further training. The validation loss, on the other hand, reaches a minimum and plateaus. At a certain epoch, there is no return (or even a negative return) to further training. Our model will only start to memorize the training data and will not be able to generalize to testing data.
Without early stopping, our model will train for longer than necessary and will overfit to the training data.
Another point we can see from the training curves is that our model is not overfitting greatly. There is some overfitting as is always be the case, but the dropout after the first trainable fully connected layer prevents the training and validation losses from diverging too much.
In the notebook I take care of some boring — but necessary — details of saving and loading PyTorch models, but here we’ll move right to the best part: making predictions on new images. We know our model does well on training and even validation data, but the ultimate test is how it performs on a hold-out testing set it has not seen before. We saved 25% of the data for the purpose of determining if our model can generalize to new data.
Predicting with a trained model is pretty simple. We use the same syntax as for training and validation:
for data, targets in testloader: log_ps = model(data) # Convert to probabilities ps = torch.exp(log_ps)ps.shape()(128, 100)
The shape of our probabilities are ( batch_size , n_classes ) because we have a probability for every class. We can find the accuracy by finding the highest probability for each example and compare these to the labels:
# Find predictions and correctpred = torch.max(ps, dim=1)equals = pred == targets# Calculate accuracyaccuracy = torch.mean(equals)
When diagnosing a network used for object recognition, it can be helpful to look at both overall performance on the test set and individual predictions.
Here are two predictions the model nails:
These are pretty easy, so I’m glad the model has no trouble!
We don’t just want to focus on the correct predictions and we’ll take a look at some wrong outputs shortly. For now let’s evaluate the performance on the entire test set. For this, we want to iterate over the test DataLoader and calculate the loss and accuracy for every example.
Convolutional neural networks for object recognition are generally measured in terms of topk accuracy. This refers to the whether or not the real class was in the k most likely predicted classes. For example, top 5 accuracy is the % the right class was in the 5 highest probability predictions. You can get the topk most likely probabilities and classes from a PyTorch tensor as follows:
top_5_ps, top_5_classes = ps.topk(5, dim=1)top_5_ps.shape(128, 5)
Evaluating the model on the entire testing set, we calculate the metrics:
Final test top 1 weighted accuracy = 88.65%Final test top 5 weighted accuracy = 98.00%Final test cross entropy per image = 0.3772.
These compare favorably to the near 90% top 1 accuracy on the validation data. Overall, we conclude our pre-trained model was able to successfully transfer its knowledge from Imagenet to our smaller dataset.
Although the model does well, there’s likely steps to take which can make it even better. Often, the best way to figure out how to improve a model is to investigate its errors (note: this is also an effective self-improvement method.)
Our model isn’t great at identifying crocodiles, so let’s look at some test predictions from this category:
Given the subtle distinction between crocodile and crocodile_head , and the difficulty of the second image, I’d say our model is not entirely unreasonable in these predictions. The ultimate goal in image recognition is to exceed human capabilities, and our model is nearly there!
Finally, we’d expect the model to perform better on categories with more images, so we can look at a graph of accuracy in a given category versus the number of training images in that category:
There does appear to be a positive correlation between the number of training images and the top 1 test accuracy. This indicates that more training data augmentation could be helpful, or, even that we should use test time augmentation. We could also try a different pre-trained model, or build another custom classifier. At the moment, deep learning is still an empirical field meaning experimentation is often required!
While there are easier deep learning libraries to use, the benefits of PyTorch are speed, control over every aspect of model architecture / training, efficient implementation of backpropagation with tensor auto differentiation, and ease of debugging code due to the dynamic nature of PyTorch graphs. For production code or your own projects, I’m not sure there is yet a compelling argument for using PyTorch instead of a library with a gentler learning curve such as Keras, but it’s helpful to know how to use different options.
Through this project, we were able to see the basics of using PyTorch as well as the concept of transfer learning, an effective method for object recognition. Instead of training a model from scratch, we can use existing architectures that have been trained on a large dataset and then tune them for our task. This reduces the time to train and often results in better overall performance. The outcome of this project is some knowledge of transfer learning and PyTorch that we can build on to build more complex applications.
We truly live in an incredible age for deep learning, where anyone can build deep learning models with easily available resources! Now get out there and take advantage of these resources by building your own project.
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or through my personal website willk.online. | [
{
"code": null,
"e": 527,
"s": 172,
"text": "Although Keras is a great library with a simple API for building neural networks, the recent excitement about PyTorch finally got me interested in exploring this library. While I’m one to blindly follow the hype, the adoption by researchers and inclusion in the fast.ai library convinced me there must be something behind this new entry in deep learning."
},
{
"code": null,
"e": 925,
"s": 527,
"text": "Since the best way to learn a new technology is by using it to solve a problem, my efforts to learn PyTorch started out with a simple project: use a pre-trained convolutional neural network for an object recognition task. In this article, we’ll see how to use PyTorch to accomplish this goal, along the way, learning a little about the library and about the important concept of transfer learning."
},
{
"code": null,
"e": 1152,
"s": 925,
"text": "While PyTorch might not be for everyone, at this point it’s impossible to say which deep learning library will come out on top, and being able to quickly learn and use different tools is crucial to succeed as a data scientist."
},
{
"code": null,
"e": 1325,
"s": 1152,
"text": "The complete code for this project is available as a Jupyter Notebook on GitHub. This project was born out of my participation in the Udacity PyTorch scholarship challenge."
},
{
"code": null,
"e": 1749,
"s": 1325,
"text": "Our task will be to train a convolutional neural network (CNN) that can identify objects in images. We’ll be using the Caltech 101 dataset which has images in 101 categories. Most categories only have 50 images which typically isn’t enough for a neural network to learn to high accuracy. Therefore, instead of building and training a CNN from scratch, we’ll use a pre-built and pre-trained model applying transfer learning."
},
{
"code": null,
"e": 2273,
"s": 1749,
"text": "The basic premise of transfer learning is simple: take a model trained on a large dataset and transfer its knowledge to a smaller dataset. For object recognition with a CNN, we freeze the early convolutional layers of the network and only train the last few layers which make a prediction. The idea is the convolutional layers extract general, low-level features that are applicable across images — such as edges, patterns, gradients — and the later layers identify specific features within an image such as eyes or wheels."
},
{
"code": null,
"e": 2645,
"s": 2273,
"text": "Thus, we can use a network trained on unrelated categories in a massive dataset (usually Imagenet) and apply it to our own problem because there are universal, low-level features shared between images. The images in the Caltech 101 dataset are very similar to those in the Imagenet dataset and the knowledge a model learns on Imagenet should easily transfer to this task."
},
{
"code": null,
"e": 2724,
"s": 2645,
"text": "Following is the general outline for transfer learning for object recognition:"
},
{
"code": null,
"e": 3041,
"s": 2724,
"text": "Load in a pre-trained CNN model trained on a large datasetFreeze parameters (weights) in model’s lower convolutional layersAdd custom classifier with several layers of trainable parameters to modelTrain classifier layers on training data available for taskFine-tune hyperparameters and unfreeze more layers as needed"
},
{
"code": null,
"e": 3100,
"s": 3041,
"text": "Load in a pre-trained CNN model trained on a large dataset"
},
{
"code": null,
"e": 3166,
"s": 3100,
"text": "Freeze parameters (weights) in model’s lower convolutional layers"
},
{
"code": null,
"e": 3241,
"s": 3166,
"text": "Add custom classifier with several layers of trainable parameters to model"
},
{
"code": null,
"e": 3301,
"s": 3241,
"text": "Train classifier layers on training data available for task"
},
{
"code": null,
"e": 3362,
"s": 3301,
"text": "Fine-tune hyperparameters and unfreeze more layers as needed"
},
{
"code": null,
"e": 3577,
"s": 3362,
"text": "This approach has proven successful for a wide range of domains. It’s a great tool to have in your arsenal and generally the first approach that should be tried when confronted with a new image recognition problem."
},
{
"code": null,
"e": 4039,
"s": 3577,
"text": "With all data science problems, formatting the data correctly will determine the success or failure of the project. Fortunately, the Caltech 101 dataset images are clean and stored in the correct format. If we correctly set up the data directories, PyTorch makes it simple to associate the correct labels with each class. I separated the data into training, validation, and testing sets with a 50%, 25%, 25% split and then structured the directories as follows:"
},
{
"code": null,
"e": 4221,
"s": 4039,
"text": "/datadir /train /class1 /class2 . . /valid /class1 /class2 . . /test /class1 /class2 . ."
},
{
"code": null,
"e": 4329,
"s": 4221,
"text": "The number of training images by classes is below (I use the terms classes and categories interchangeably):"
},
{
"code": null,
"e": 4558,
"s": 4329,
"text": "We expect the model to do better on classes with more examples because it can better learn to map features to labels. To deal with the limited number of training examples we’ll use data augmentation during training (more later)."
},
{
"code": null,
"e": 4637,
"s": 4558,
"text": "As another bit of data exploration, we can also look at the size distribution."
},
{
"code": null,
"e": 4836,
"s": 4637,
"text": "Imagenet models need an input size of 224 x 224 so one of the preprocessing steps will be to resize the images. Preprocessing is also where we will implement data augmentation for our training data."
},
{
"code": null,
"e": 5234,
"s": 4836,
"text": "The idea of data augmentation is to artificially increase the number of training images our model sees by applying random transformations to the images. For example, we can randomly rotate or crop the images or flip them horizontally. We want our model to distinguish the objects regardless of orientation and data augmentation can also make a model invariant to transformations of the input data."
},
{
"code": null,
"e": 5300,
"s": 5234,
"text": "An elephant is still an elephant no matter which way it’s facing!"
},
{
"code": null,
"e": 5804,
"s": 5300,
"text": "Augmentation is generally only done during training (although test time augmentation is possible in the fast.ai library). Each epoch — one iteration through all the training images — a different random transformation is applied to each training image. This means that if we iterate through the data 20 times, our model will see 20 slightly different versions of each image. The overall result should be a model that learns the objects themselves and not how they are presented or artifacts in the image."
},
{
"code": null,
"e": 6168,
"s": 5804,
"text": "This is the most important step of working with image data. During image preprocessing, we simultaneously prepare the images for our network and apply data augmentation to the training set. Each model will have different input requirements, but if we read through what Imagenet requires, we figure out that our images need to be 224x224 and normalized to a range."
},
{
"code": null,
"e": 6313,
"s": 6168,
"text": "To process an image in PyTorch, we use transforms , simple operations applied to arrays. The validation (and testing) transforms are as follows:"
},
{
"code": null,
"e": 6320,
"s": 6313,
"text": "Resize"
},
{
"code": null,
"e": 6345,
"s": 6320,
"text": "Center crop to 224 x 224"
},
{
"code": null,
"e": 6365,
"s": 6345,
"text": "Convert to a tensor"
},
{
"code": null,
"e": 6408,
"s": 6365,
"text": "Normalize with mean and standard deviation"
},
{
"code": null,
"e": 6589,
"s": 6408,
"text": "The end result of passing through these transforms are tensors that can go into our network. The training transformations are similar but with the addition of random augmentations."
},
{
"code": null,
"e": 6654,
"s": 6589,
"text": "First up, we define the training and validation transformations:"
},
{
"code": null,
"e": 6957,
"s": 6654,
"text": "Then, we create datasets and DataLoaders . By using datasets.ImageFolder to make a dataset, PyTorch will automatically associate images with the correct labels provided our directory is set up as above. The datasets are then passed to a DataLoader , an iterator that yield batches of images and labels."
},
{
"code": null,
"e": 7030,
"s": 6957,
"text": "We can see the iterative behavior of the DataLoader using the following:"
},
{
"code": null,
"e": 7219,
"s": 7030,
"text": "# Iterate through the dataloader oncetrainiter = iter(dataloaders['train'])features, labels = next(trainiter)features.shape, labels.shape(torch.Size([128, 3, 224, 224]), torch.Size([128]))"
},
{
"code": null,
"e": 7582,
"s": 7219,
"text": "The shape of a batch is (batch_size, color_channels, height, width). During training, validation, and eventually testing, we’ll iterate through the DataLoaders, with one pass through the complete dataset comprising one epoch. Every epoch, the training DataLoader will apply a slightly different random transformation to the images for training data augmentation."
},
{
"code": null,
"e": 7932,
"s": 7582,
"text": "With our data in shape, we next turn our attention to the model. For this, we’ll use a pre-trained convolutional neural network. PyTorch has a number of models that have already been trained on millions of images from 1000 classes in Imagenet. The complete list of models can be seen here. The performance of these models on Imagenet is shown below:"
},
{
"code": null,
"e": 8168,
"s": 7932,
"text": "For this implementation, we’ll be using the VGG-16. Although it didn’t record the lowest error, I found it worked well for the task and was quicker to train than other models. The process to use a pre-trained model is well-established:"
},
{
"code": null,
"e": 8618,
"s": 8168,
"text": "Load in pre-trained weights from a network trained on a large datasetFreeze all the weights in the lower (convolutional) layers: the layers to freeze are adjusted depending on similarity of new task to original datasetReplace the upper layers of the network with a custom classifier: the number of outputs must be set equal to the number of classesTrain only the custom classifier layers for the task thereby optimizing the model for smaller dataset"
},
{
"code": null,
"e": 8688,
"s": 8618,
"text": "Load in pre-trained weights from a network trained on a large dataset"
},
{
"code": null,
"e": 8838,
"s": 8688,
"text": "Freeze all the weights in the lower (convolutional) layers: the layers to freeze are adjusted depending on similarity of new task to original dataset"
},
{
"code": null,
"e": 8969,
"s": 8838,
"text": "Replace the upper layers of the network with a custom classifier: the number of outputs must be set equal to the number of classes"
},
{
"code": null,
"e": 9071,
"s": 8969,
"text": "Train only the custom classifier layers for the task thereby optimizing the model for smaller dataset"
},
{
"code": null,
"e": 9124,
"s": 9071,
"text": "Loading in a pre-trained model in PyTorch is simple:"
},
{
"code": null,
"e": 9191,
"s": 9124,
"text": "from torchvision import modelsmodel = model.vgg16(pretrained=True)"
},
{
"code": null,
"e": 9347,
"s": 9191,
"text": "This model has over 130 million parameters, but we’ll train only the very last few fully-connected layers. Initially, we freeze all of the model’s weights:"
},
{
"code": null,
"e": 9433,
"s": 9347,
"text": "# Freeze model weightsfor param in model.parameters(): param.requires_grad = False"
},
{
"code": null,
"e": 9502,
"s": 9433,
"text": "Then, we add on our own custom classifier with the following layers:"
},
{
"code": null,
"e": 9564,
"s": 9502,
"text": "Fully connected with ReLU activation, shape = (n_inputs, 256)"
},
{
"code": null,
"e": 9600,
"s": 9564,
"text": "Dropout with 40% chance of dropping"
},
{
"code": null,
"e": 9666,
"s": 9600,
"text": "Fully connected with log softmax output, shape = (256, n_classes)"
},
{
"code": null,
"e": 9972,
"s": 9666,
"text": "import torch.nn as nn# Add on classifiermodel.classifier[6] = nn.Sequential( nn.Linear(n_inputs, 256), nn.ReLU(), nn.Dropout(0.4), nn.Linear(256, n_classes), nn.LogSoftmax(dim=1))"
},
{
"code": null,
"e": 10269,
"s": 9972,
"text": "When the extra layers are added to the model, they are set to trainable by default ( require_grad=True ). For the VGG-16, we’re only changing the very last original fully-connected layer. All of the weights in the convolutional layers and the the first 5 fully-connected layers are not trainable."
},
{
"code": null,
"e": 10735,
"s": 10269,
"text": "# Only training classifier[6]model.classifierSequential( (0): Linear(in_features=25088, out_features=4096, bias=True) (1): ReLU(inplace) (2): Dropout(p=0.5) (3): Linear(in_features=4096, out_features=4096, bias=True) (4): ReLU(inplace) (5): Dropout(p=0.5) (6): Sequential( (0): Linear(in_features=4096, out_features=256, bias=True) (1): ReLU() (2): Dropout(p=0.4) (3): Linear(in_features=256, out_features=100, bias=True) (4): LogSoftmax() ))"
},
{
"code": null,
"e": 10931,
"s": 10735,
"text": "The final outputs from the network are log probabilities for each of the 100 classes in our dataset. The model has a total of 135 million parameters, of which just over 1 million will be trained."
},
{
"code": null,
"e": 11287,
"s": 10931,
"text": "# Find total parameters and trainable parameterstotal_params = sum(p.numel() for p in model.parameters())print(f'{total_params:,} total parameters.')total_trainable_params = sum( p.numel() for p in model.parameters() if p.requires_grad)print(f'{total_trainable_params:,} training parameters.')135,335,076 total parameters.1,074,532 training parameters."
},
{
"code": null,
"e": 11566,
"s": 11287,
"text": "One of the best aspects of PyTorch is the ease of moving different parts of a model to one or more gpus so you can make full use of your hardware. Since I’m using 2 gpus for training, I first move the model to cuda and then create a DataParallel model distributed over the gpus:"
},
{
"code": null,
"e": 11660,
"s": 11566,
"text": "# Move to gpumodel = model.to('cuda')# Distribute across 2 gpusmodel = nn.DataParallel(model)"
},
{
"code": null,
"e": 11793,
"s": 11660,
"text": "(This notebook should be run on a gpu to complete in a reasonable amount of time. The speedup over a cpu can easily by 10x or more.)"
},
{
"code": null,
"e": 12322,
"s": 11793,
"text": "The training loss (the error or difference between predictions and true values) is the negative log likelihood (NLL). (The NLL loss in PyTorch expects log probabilities, so we pass in the raw output from the model’s final layer.) PyTorch uses automatic differentiation which means that tensors keep track of not only their value, but also every operation (multiply, addition, activation, etc.) which contributes to the value. This means we can compute the gradient for any tensor in the network with respect to any prior tensor."
},
{
"code": null,
"e": 12831,
"s": 12322,
"text": "What this means in practice is that the loss tracks not only the error, but also the contribution to the error by each weight and bias in the model. After we calculate the loss, we can then find the gradients of the loss with respect to each model parameter, a process known as backpropagation. Once we have the gradients, we use them to update the parameters with the optimizer. (If this doesn’t sink in at first, don’t worry, it takes a little while to grasp! This powerpoint helps to clarify some points.)"
},
{
"code": null,
"e": 13183,
"s": 12831,
"text": "The optimizer is Adam, an efficient variant of gradient descent that generally does not require hand-tuning the learning rate. During training, the optimizer uses the gradients of the loss to try and reduce the error (“optimize”) of the model output by adjusting the parameters. Only the parameters we added in the custom classifier will be optimized."
},
{
"code": null,
"e": 13234,
"s": 13183,
"text": "The loss and optimizer are initialized as follows:"
},
{
"code": null,
"e": 13346,
"s": 13234,
"text": "from torch import optim# Loss and optimizercriteration = nn.NLLLoss()optimizer = optim.Adam(model.parameters())"
},
{
"code": null,
"e": 13480,
"s": 13346,
"text": "With the pre-trained model, the custom classifier, the loss, the optimizer, and most importantly, the data, we’re ready for training."
},
{
"code": null,
"e": 13996,
"s": 13480,
"text": "Model training in PyTorch is a little more hands-on than in Keras because we have to do the backpropagation and parameter update step ourselves. The main loop iterates over a number of epochs and on each epoch we iterate through the train DataLoader . The DataLoader yields one batch of data and targets which we pass through the model. After each training batch, we calculate the loss, backpropagate the gradients of the loss with respect to the model parameters, and then update the parameters with the optimizer."
},
{
"code": null,
"e": 14114,
"s": 13996,
"text": "I’d encourage you to look at the notebook for the complete training details, but the basic pseudo-code is as follows:"
},
{
"code": null,
"e": 14377,
"s": 14114,
"text": "We can continue to iterate through the data until we reach a given number of epochs. However, one problem with this approach is that our model will eventually start overfitting to the training data. To prevent this, we use our validation data and early stopping."
},
{
"code": null,
"e": 14950,
"s": 14377,
"text": "Early stopping means halting training when the validation loss has not decreased for a number of epochs. As we continue training, the training loss will only decrease, but the validation loss will eventually reach a minimum and plateau or start to increase. We ideally want to stop training when the validation loss is at a minimum in the hope that this model will generalize best to the testing data. When using early stopping, every epoch in which the validation loss decreases, we save the parameters so we can later retrieve those with the best validation performance."
},
{
"code": null,
"e": 15328,
"s": 14950,
"text": "We implement early stopping by iterating through the validation DataLoader at the end of each training epoch. We calculate the validation loss and compare this to the lowest validation loss. If the loss is the lowest so far, we save the model. If the loss has not improved for a certain number of epochs, we halt training and return the best model which has been saved to disk."
},
{
"code": null,
"e": 15393,
"s": 15328,
"text": "Again, the complete code is in the notebook, but pseudo-code is:"
},
{
"code": null,
"e": 15524,
"s": 15393,
"text": "To see the benefits of early stopping, we can look at the training curves showing the training and validation losses and accuracy:"
},
{
"code": null,
"e": 15873,
"s": 15524,
"text": "As expected, the training loss only continues to decrease with further training. The validation loss, on the other hand, reaches a minimum and plateaus. At a certain epoch, there is no return (or even a negative return) to further training. Our model will only start to memorize the training data and will not be able to generalize to testing data."
},
{
"code": null,
"e": 15983,
"s": 15873,
"text": "Without early stopping, our model will train for longer than necessary and will overfit to the training data."
},
{
"code": null,
"e": 16264,
"s": 15983,
"text": "Another point we can see from the training curves is that our model is not overfitting greatly. There is some overfitting as is always be the case, but the dropout after the first trainable fully connected layer prevents the training and validation losses from diverging too much."
},
{
"code": null,
"e": 16703,
"s": 16264,
"text": "In the notebook I take care of some boring — but necessary — details of saving and loading PyTorch models, but here we’ll move right to the best part: making predictions on new images. We know our model does well on training and even validation data, but the ultimate test is how it performs on a hold-out testing set it has not seen before. We saved 25% of the data for the purpose of determining if our model can generalize to new data."
},
{
"code": null,
"e": 16808,
"s": 16703,
"text": "Predicting with a trained model is pretty simple. We use the same syntax as for training and validation:"
},
{
"code": null,
"e": 16941,
"s": 16808,
"text": "for data, targets in testloader: log_ps = model(data) # Convert to probabilities ps = torch.exp(log_ps)ps.shape()(128, 100)"
},
{
"code": null,
"e": 17160,
"s": 16941,
"text": "The shape of our probabilities are ( batch_size , n_classes ) because we have a probability for every class. We can find the accuracy by finding the highest probability for each example and compare these to the labels:"
},
{
"code": null,
"e": 17291,
"s": 17160,
"text": "# Find predictions and correctpred = torch.max(ps, dim=1)equals = pred == targets# Calculate accuracyaccuracy = torch.mean(equals)"
},
{
"code": null,
"e": 17444,
"s": 17291,
"text": "When diagnosing a network used for object recognition, it can be helpful to look at both overall performance on the test set and individual predictions."
},
{
"code": null,
"e": 17486,
"s": 17444,
"text": "Here are two predictions the model nails:"
},
{
"code": null,
"e": 17547,
"s": 17486,
"text": "These are pretty easy, so I’m glad the model has no trouble!"
},
{
"code": null,
"e": 17827,
"s": 17547,
"text": "We don’t just want to focus on the correct predictions and we’ll take a look at some wrong outputs shortly. For now let’s evaluate the performance on the entire test set. For this, we want to iterate over the test DataLoader and calculate the loss and accuracy for every example."
},
{
"code": null,
"e": 18215,
"s": 17827,
"text": "Convolutional neural networks for object recognition are generally measured in terms of topk accuracy. This refers to the whether or not the real class was in the k most likely predicted classes. For example, top 5 accuracy is the % the right class was in the 5 highest probability predictions. You can get the topk most likely probabilities and classes from a PyTorch tensor as follows:"
},
{
"code": null,
"e": 18281,
"s": 18215,
"text": "top_5_ps, top_5_classes = ps.topk(5, dim=1)top_5_ps.shape(128, 5)"
},
{
"code": null,
"e": 18355,
"s": 18281,
"text": "Evaluating the model on the entire testing set, we calculate the metrics:"
},
{
"code": null,
"e": 18486,
"s": 18355,
"text": "Final test top 1 weighted accuracy = 88.65%Final test top 5 weighted accuracy = 98.00%Final test cross entropy per image = 0.3772."
},
{
"code": null,
"e": 18694,
"s": 18486,
"text": "These compare favorably to the near 90% top 1 accuracy on the validation data. Overall, we conclude our pre-trained model was able to successfully transfer its knowledge from Imagenet to our smaller dataset."
},
{
"code": null,
"e": 18929,
"s": 18694,
"text": "Although the model does well, there’s likely steps to take which can make it even better. Often, the best way to figure out how to improve a model is to investigate its errors (note: this is also an effective self-improvement method.)"
},
{
"code": null,
"e": 19037,
"s": 18929,
"text": "Our model isn’t great at identifying crocodiles, so let’s look at some test predictions from this category:"
},
{
"code": null,
"e": 19317,
"s": 19037,
"text": "Given the subtle distinction between crocodile and crocodile_head , and the difficulty of the second image, I’d say our model is not entirely unreasonable in these predictions. The ultimate goal in image recognition is to exceed human capabilities, and our model is nearly there!"
},
{
"code": null,
"e": 19511,
"s": 19317,
"text": "Finally, we’d expect the model to perform better on categories with more images, so we can look at a graph of accuracy in a given category versus the number of training images in that category:"
},
{
"code": null,
"e": 19932,
"s": 19511,
"text": "There does appear to be a positive correlation between the number of training images and the top 1 test accuracy. This indicates that more training data augmentation could be helpful, or, even that we should use test time augmentation. We could also try a different pre-trained model, or build another custom classifier. At the moment, deep learning is still an empirical field meaning experimentation is often required!"
},
{
"code": null,
"e": 20461,
"s": 19932,
"text": "While there are easier deep learning libraries to use, the benefits of PyTorch are speed, control over every aspect of model architecture / training, efficient implementation of backpropagation with tensor auto differentiation, and ease of debugging code due to the dynamic nature of PyTorch graphs. For production code or your own projects, I’m not sure there is yet a compelling argument for using PyTorch instead of a library with a gentler learning curve such as Keras, but it’s helpful to know how to use different options."
},
{
"code": null,
"e": 20987,
"s": 20461,
"text": "Through this project, we were able to see the basics of using PyTorch as well as the concept of transfer learning, an effective method for object recognition. Instead of training a model from scratch, we can use existing architectures that have been trained on a large dataset and then tune them for our task. This reduces the time to train and often results in better overall performance. The outcome of this project is some knowledge of transfer learning and PyTorch that we can build on to build more complex applications."
},
{
"code": null,
"e": 21204,
"s": 20987,
"text": "We truly live in an incredible age for deep learning, where anyone can build deep learning models with easily available resources! Now get out there and take advantage of these resources by building your own project."
}
]
|
JavaFX | Point2D Class - GeeksforGeeks | 30 Jul, 2021
Point2D class is a part of JavaFX. This class defines a 2-dimensional point in space. The Point2D class represents a 2D point by its x, y coordinates. It inherits java.lang.Object class.Constructor of the class:
Point2D(double x, double y): Create a point2D object with specified x and y coordinates.
Commonly Used Methods:
Below programs will illustrate the use of the Point2D class:
1.Java program to create a point 2D object and display its coordinates and find its distance from origin: In this program we create a Point2D object named point2d_1 by using its x, y coordinates as arguments. We will get the values of x, y using the getX(), getY() function and after that display it. We are also calculating the distance of the points from the origin.
Java
// Java program to create a point 2D// object and display its coordinates// and find its distance from originimport javafx.geometry.Point2D; public class Point2D_1 { // Main Method public static void main(String args[]) { // Create a point2D object Point2D point2d_1 = new Point2D(20.0f, 150.0f); double x, y; // get the coordinates of the point x = point2d_1.getX(); y = point2d_1.getY(); // display the coordinates of the point System.out.println("x coordinate = " + x + ", y coordinate = " + y); // print its distance from origin System.out.println("distance from origin = " + point2d_1.distance(0, 0)); }}
Output:
x coordinate = 20.0, y coordinate = 150.0
distance from origin = 151.32745950421557
2.Java program to create 3 Point2D objects and display their coordinates and distance from the origin and check which of the 3 points are similar and their distances between two points: In this program we create 3 Point2D object named point2d_1, point2d_2, point2d_3 by passing its x, y coordinates as arguments. We get the x, y values using the getX(), getY() function and then display it. We are also calculating the distance of the point from the origin and displaying it for each of the three points. We are also displaying whether any two points are equal or not using equals() function and the distance between two points using the distance() function.
Java
// Java program to create 3 Point2D objects and display// their coordinates and distance from origin and// check which of the 3 points are similar and// their distances between two pointsimport javafx.geometry.Point2D; public class Point2D_2 { // Main Method public static void main(String args[]) { // Create three point2D objects Point2D point2d_1 = new Point2D(120.0f, 50.0f); Point2D point2d_2 = new Point2D(120.0f, 50.0f); Point2D point2d_3 = new Point2D(200.0f, 120.0f); // Display the coordinates of the 3 points display(point2d_1); display(point2d_2); display(point2d_3); // Check whether any point is equal to other or not System.out.println("Point 1 equals Point 2 = " + point2d_1.equals(point2d_2)); System.out.println("Point 2 equals Point 3 = " + point2d_2.equals(point2d_3)); System.out.println("Point 3 equals Point 1 = " + point2d_3.equals(point2d_1)); // distance between two points System.out.println("Distance between point 1 and point 2 = " + point2d_1.distance(point2d_2)); System.out.println("Distance between point 2 and point 3 = " + point2d_2.distance(point2d_3)); System.out.println("Distance between point 3 and point 1 = " + point2d_3.distance(point2d_1)); } // display method public static void display(Point2D point2d) { double x, y; // get the coordinates of the point x = point2d.getX(); y = point2d.getY(); // display the coordinates of the point System.out.println("x coordinate = " + x + ", y coordinate = " + y); // print its distance from origin System.out.println("Distance from origin = " + point2d.distance(0, 0)); }}
Output:
x coordinate = 120.0, y coordinate = 50.0
Distance from origin = 130.0
x coordinate = 120.0, y coordinate = 50.0
Distance from origin = 130.0
x coordinate = 200.0, y coordinate = 120.0
Distance from origin = 233.23807579381202
Point 1 equals Point 2 = true
Point 2 equals Point 3 = false
Point 3 equals Point 1 = false
Distance between point 1 and point 2 = 0.0
Distance between point 2 and point 3 = 106.30145812734649
Distance between point 3 and point 1 = 106.30145812734649
Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/geometry/Point2D.html
simmytarika5
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
HashMap get() Method in Java
Comparator Interface in Java with Examples
Strings in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23973,
"s": 23945,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 24187,
"s": 23973,
"text": "Point2D class is a part of JavaFX. This class defines a 2-dimensional point in space. The Point2D class represents a 2D point by its x, y coordinates. It inherits java.lang.Object class.Constructor of the class: "
},
{
"code": null,
"e": 24276,
"s": 24187,
"text": "Point2D(double x, double y): Create a point2D object with specified x and y coordinates."
},
{
"code": null,
"e": 24299,
"s": 24276,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 24362,
"s": 24299,
"text": "Below programs will illustrate the use of the Point2D class: "
},
{
"code": null,
"e": 24731,
"s": 24362,
"text": "1.Java program to create a point 2D object and display its coordinates and find its distance from origin: In this program we create a Point2D object named point2d_1 by using its x, y coordinates as arguments. We will get the values of x, y using the getX(), getY() function and after that display it. We are also calculating the distance of the points from the origin."
},
{
"code": null,
"e": 24736,
"s": 24731,
"text": "Java"
},
{
"code": "// Java program to create a point 2D// object and display its coordinates// and find its distance from originimport javafx.geometry.Point2D; public class Point2D_1 { // Main Method public static void main(String args[]) { // Create a point2D object Point2D point2d_1 = new Point2D(20.0f, 150.0f); double x, y; // get the coordinates of the point x = point2d_1.getX(); y = point2d_1.getY(); // display the coordinates of the point System.out.println(\"x coordinate = \" + x + \", y coordinate = \" + y); // print its distance from origin System.out.println(\"distance from origin = \" + point2d_1.distance(0, 0)); }}",
"e": 25478,
"s": 24736,
"text": null
},
{
"code": null,
"e": 25487,
"s": 25478,
"text": "Output: "
},
{
"code": null,
"e": 25571,
"s": 25487,
"text": "x coordinate = 20.0, y coordinate = 150.0\ndistance from origin = 151.32745950421557"
},
{
"code": null,
"e": 26231,
"s": 25571,
"text": "2.Java program to create 3 Point2D objects and display their coordinates and distance from the origin and check which of the 3 points are similar and their distances between two points: In this program we create 3 Point2D object named point2d_1, point2d_2, point2d_3 by passing its x, y coordinates as arguments. We get the x, y values using the getX(), getY() function and then display it. We are also calculating the distance of the point from the origin and displaying it for each of the three points. We are also displaying whether any two points are equal or not using equals() function and the distance between two points using the distance() function. "
},
{
"code": null,
"e": 26236,
"s": 26231,
"text": "Java"
},
{
"code": "// Java program to create 3 Point2D objects and display// their coordinates and distance from origin and// check which of the 3 points are similar and// their distances between two pointsimport javafx.geometry.Point2D; public class Point2D_2 { // Main Method public static void main(String args[]) { // Create three point2D objects Point2D point2d_1 = new Point2D(120.0f, 50.0f); Point2D point2d_2 = new Point2D(120.0f, 50.0f); Point2D point2d_3 = new Point2D(200.0f, 120.0f); // Display the coordinates of the 3 points display(point2d_1); display(point2d_2); display(point2d_3); // Check whether any point is equal to other or not System.out.println(\"Point 1 equals Point 2 = \" + point2d_1.equals(point2d_2)); System.out.println(\"Point 2 equals Point 3 = \" + point2d_2.equals(point2d_3)); System.out.println(\"Point 3 equals Point 1 = \" + point2d_3.equals(point2d_1)); // distance between two points System.out.println(\"Distance between point 1 and point 2 = \" + point2d_1.distance(point2d_2)); System.out.println(\"Distance between point 2 and point 3 = \" + point2d_2.distance(point2d_3)); System.out.println(\"Distance between point 3 and point 1 = \" + point2d_3.distance(point2d_1)); } // display method public static void display(Point2D point2d) { double x, y; // get the coordinates of the point x = point2d.getX(); y = point2d.getY(); // display the coordinates of the point System.out.println(\"x coordinate = \" + x + \", y coordinate = \" + y); // print its distance from origin System.out.println(\"Distance from origin = \" + point2d.distance(0, 0)); }}",
"e": 28217,
"s": 26236,
"text": null
},
{
"code": null,
"e": 28226,
"s": 28217,
"text": "Output: "
},
{
"code": null,
"e": 28704,
"s": 28226,
"text": "x coordinate = 120.0, y coordinate = 50.0\nDistance from origin = 130.0\nx coordinate = 120.0, y coordinate = 50.0\nDistance from origin = 130.0\nx coordinate = 200.0, y coordinate = 120.0\nDistance from origin = 233.23807579381202\nPoint 1 equals Point 2 = true\nPoint 2 equals Point 3 = false\nPoint 3 equals Point 1 = false\nDistance between point 1 and point 2 = 0.0\nDistance between point 2 and point 3 = 106.30145812734649\nDistance between point 3 and point 1 = 106.30145812734649"
},
{
"code": null,
"e": 28870,
"s": 28704,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/geometry/Point2D.html "
},
{
"code": null,
"e": 28883,
"s": 28870,
"text": "simmytarika5"
},
{
"code": null,
"e": 28890,
"s": 28883,
"text": "JavaFX"
},
{
"code": null,
"e": 28895,
"s": 28890,
"text": "Java"
},
{
"code": null,
"e": 28900,
"s": 28895,
"text": "Java"
},
{
"code": null,
"e": 28998,
"s": 28900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29044,
"s": 28998,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29059,
"s": 29044,
"text": "Stream In Java"
},
{
"code": null,
"e": 29080,
"s": 29059,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29099,
"s": 29080,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29116,
"s": 29099,
"text": "Generics in Java"
},
{
"code": null,
"e": 29146,
"s": 29116,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29175,
"s": 29146,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 29218,
"s": 29175,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29234,
"s": 29218,
"text": "Strings in Java"
}
]
|
Objective-C Data Types | In the Objective-C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
The types in Objective-C can be classified as follows −
Basic Types −
They are arithmetic types and consist of the two types: (a) integer types and (b) floating-point types.
Enumerated types −
They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program.
The type void −
The type specifier void indicates that no value is available.
Derived types −
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.
The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters.
Following table gives you details about standard integer types with its storage sizes and value ranges −
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine −
#import <Foundation/Foundation.h>
int main() {
NSLog(@"Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
2013-09-07 22:21:39.155 demo[1340] Storage size for int : 4
Following table gives you details about standard float-point types with storage sizes and value ranges and their precision −
The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values −
#import <Foundation/Foundation.h>
int main() {
NSLog(@"Storage size for float : %d \n", sizeof(float));
return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
2013-09-07 22:22:21.729 demo[3927] Storage size for float : 4
The void type specifies that no value is available. It is used in three kinds of situations −
There are various functions in Objective-C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);
There are various functions in Objective-C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void);
The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters.
18 Lectures
1 hours
PARTHA MAJUMDAR
6 Lectures
25 mins
Ken Burke
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2822,
"s": 2560,
"text": "In the Objective-C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted."
},
{
"code": null,
"e": 2878,
"s": 2822,
"text": "The types in Objective-C can be classified as follows −"
},
{
"code": null,
"e": 2892,
"s": 2878,
"text": "Basic Types −"
},
{
"code": null,
"e": 2996,
"s": 2892,
"text": "They are arithmetic types and consist of the two types: (a) integer types and (b) floating-point types."
},
{
"code": null,
"e": 3015,
"s": 2996,
"text": "Enumerated types −"
},
{
"code": null,
"e": 3167,
"s": 3015,
"text": "They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program."
},
{
"code": null,
"e": 3183,
"s": 3167,
"text": "The type void −"
},
{
"code": null,
"e": 3245,
"s": 3183,
"text": "The type specifier void indicates that no value is available."
},
{
"code": null,
"e": 3261,
"s": 3245,
"text": "Derived types −"
},
{
"code": null,
"e": 3371,
"s": 3261,
"text": "They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types."
},
{
"code": null,
"e": 3645,
"s": 3371,
"text": "The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters."
},
{
"code": null,
"e": 3750,
"s": 3645,
"text": "Following table gives you details about standard integer types with its storage sizes and value ranges −"
},
{
"code": null,
"e": 4008,
"s": 3750,
"text": "To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine −"
},
{
"code": null,
"e": 4127,
"s": 4008,
"text": "#import <Foundation/Foundation.h>\n\nint main() {\n NSLog(@\"Storage size for int : %d \\n\", sizeof(int));\n return 0;\n}"
},
{
"code": null,
"e": 4219,
"s": 4127,
"text": "When you compile and execute the above program, it produces the following result on Linux −"
},
{
"code": null,
"e": 4281,
"s": 4219,
"text": "2013-09-07 22:21:39.155 demo[1340] Storage size for int : 4 \n"
},
{
"code": null,
"e": 4406,
"s": 4281,
"text": "Following table gives you details about standard float-point types with storage sizes and value ranges and their precision −"
},
{
"code": null,
"e": 4652,
"s": 4406,
"text": "The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values −"
},
{
"code": null,
"e": 4775,
"s": 4652,
"text": "#import <Foundation/Foundation.h>\n\nint main() {\n NSLog(@\"Storage size for float : %d \\n\", sizeof(float));\n return 0;\n}"
},
{
"code": null,
"e": 4867,
"s": 4775,
"text": "When you compile and execute the above program, it produces the following result on Linux −"
},
{
"code": null,
"e": 4931,
"s": 4867,
"text": "2013-09-07 22:22:21.729 demo[3927] Storage size for float : 4 \n"
},
{
"code": null,
"e": 5025,
"s": 4931,
"text": "The void type specifies that no value is available. It is used in three kinds of situations −"
},
{
"code": null,
"e": 5226,
"s": 5025,
"text": "There are various functions in Objective-C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);"
},
{
"code": null,
"e": 5384,
"s": 5226,
"text": "There are various functions in Objective-C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void);"
},
{
"code": null,
"e": 5516,
"s": 5384,
"text": "The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters."
},
{
"code": null,
"e": 5549,
"s": 5516,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5566,
"s": 5549,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 5597,
"s": 5566,
"text": "\n 6 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 5608,
"s": 5597,
"text": " Ken Burke"
},
{
"code": null,
"e": 5615,
"s": 5608,
"text": " Print"
},
{
"code": null,
"e": 5626,
"s": 5615,
"text": " Add Notes"
}
]
|
GATE | GATE-CS-2001 | Question 50 - GeeksforGeeks | 19 Nov, 2018
Consider the circuit given below with initial state Q0 =1, Q1 = Q2 = 0. The state of the circuit is given by the value 4Q2 + 2Q1 + Q0
Which one of the following is the correct state sequence of the circuit?(A) 1,3,4,6,7,5,2(B) 1,2,5,3,7,6,4(C) 1,2,7,3,5,6,4(D) 1,6,5,7,2,3,4Answer: (B)Explanation:
So ans is (B) part.Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24472,
"s": 24444,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 24606,
"s": 24472,
"text": "Consider the circuit given below with initial state Q0 =1, Q1 = Q2 = 0. The state of the circuit is given by the value 4Q2 + 2Q1 + Q0"
},
{
"code": null,
"e": 24770,
"s": 24606,
"text": "Which one of the following is the correct state sequence of the circuit?(A) 1,3,4,6,7,5,2(B) 1,2,5,3,7,6,4(C) 1,2,7,3,5,6,4(D) 1,6,5,7,2,3,4Answer: (B)Explanation:"
},
{
"code": null,
"e": 24811,
"s": 24770,
"text": "So ans is (B) part.Quiz of this Question"
},
{
"code": null,
"e": 24824,
"s": 24811,
"text": "GATE-CS-2001"
},
{
"code": null,
"e": 24842,
"s": 24824,
"text": "GATE-GATE-CS-2001"
},
{
"code": null,
"e": 24847,
"s": 24842,
"text": "GATE"
},
{
"code": null,
"e": 24945,
"s": 24847,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24954,
"s": 24945,
"text": "Comments"
},
{
"code": null,
"e": 24967,
"s": 24954,
"text": "Old Comments"
},
{
"code": null,
"e": 25001,
"s": 24967,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25034,
"s": 25001,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25076,
"s": 25034,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25118,
"s": 25076,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25160,
"s": 25118,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25194,
"s": 25160,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25228,
"s": 25194,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25270,
"s": 25228,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 25312,
"s": 25270,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
}
]
|
jQuery Effects - Animation | With jQuery, you can create custom animations.
The jQuery animate() method is used to create custom animations.
Syntax:
The required params parameter defines the CSS properties to be animated.
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
animation completes.
The following example demonstrates a simple use of the animate() method; it moves
a <div> element to the right, until it has reached a left property of 250px:
By default, all HTML elements have a static position, and cannot be moved.
To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!
Notice that multiple properties can be animated at the same time:
Is it possible to manipulate ALL CSS properties with the animate() method?
Yes, almost! However, there is one important thing to remember: all property
names must be camel-cased when used with the animate() method: You will need to
write paddingLeft instead of padding-left, marginRight instead of margin-right, and so on.
Also, color animation is not included in the core jQuery library.
If you want to animate color, you need to download the
Color
Animations plugin from jQuery.com.
It is also possible to define relative values (the value is then relative to
the element's current value). This is done by putting += or -= in front of the
value:
You can even specify a property's animation value as "show", "hide", or "toggle":
By default, jQuery comes with queue functionality for animations.
This means that if you write multiple animate() calls after each other,
jQuery creates an "internal" queue with these method calls. Then it runs the
animate calls ONE by ONE.
So, if you want to perform different animations after each other, we take
advantage of the queue functionality:
The example below first moves the <div> element to the right, and then increases the font size of the text:
Use the animate() method to move a <div> element 250 pixels to the right.
$("div").animate({: ''});
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:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 47,
"s": 0,
"text": "With jQuery, you can create custom animations."
},
{
"code": null,
"e": 112,
"s": 47,
"text": "The jQuery animate() method is used to create custom animations."
},
{
"code": null,
"e": 120,
"s": 112,
"text": "Syntax:"
},
{
"code": null,
"e": 193,
"s": 120,
"text": "The required params parameter defines the CSS properties to be animated."
},
{
"code": null,
"e": 328,
"s": 193,
"text": "The optional speed parameter specifies the duration of the effect. It can take the following values: \"slow\", \"fast\", or \nmilliseconds."
},
{
"code": null,
"e": 421,
"s": 328,
"text": "The optional callback parameter is a function to be executed after the \nanimation completes."
},
{
"code": null,
"e": 581,
"s": 421,
"text": "The following example demonstrates a simple use of the animate() method; it moves \na <div> element to the right, until it has reached a left property of 250px:"
},
{
"code": null,
"e": 780,
"s": 581,
"text": "By default, all HTML elements have a static position, and cannot be moved.\nTo manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!"
},
{
"code": null,
"e": 846,
"s": 780,
"text": "Notice that multiple properties can be animated at the same time:"
},
{
"code": null,
"e": 1335,
"s": 846,
"text": "Is it possible to manipulate ALL CSS properties with the animate() method?\nYes, almost! However, there is one important thing to remember: all property \nnames must be camel-cased when used with the animate() method: You will need to \nwrite paddingLeft instead of padding-left, marginRight instead of margin-right, and so on. \nAlso, color animation is not included in the core jQuery library.\nIf you want to animate color, you need to download the\nColor \nAnimations plugin from jQuery.com."
},
{
"code": null,
"e": 1500,
"s": 1335,
"text": "It is also possible to define relative values (the value is then relative to \nthe element's current value). This is done by putting += or -= in front of the \nvalue:"
},
{
"code": null,
"e": 1582,
"s": 1500,
"text": "You can even specify a property's animation value as \"show\", \"hide\", or \"toggle\":"
},
{
"code": null,
"e": 1648,
"s": 1582,
"text": "By default, jQuery comes with queue functionality for animations."
},
{
"code": null,
"e": 1825,
"s": 1648,
"text": "This means that if you write multiple animate() calls after each other, \njQuery creates an \"internal\" queue with these method calls. Then it runs the \nanimate calls ONE by ONE."
},
{
"code": null,
"e": 1938,
"s": 1825,
"text": "So, if you want to perform different animations after each other, we take \nadvantage of the queue functionality:"
},
{
"code": null,
"e": 2046,
"s": 1938,
"text": "The example below first moves the <div> element to the right, and then increases the font size of the text:"
},
{
"code": null,
"e": 2120,
"s": 2046,
"text": "Use the animate() method to move a <div> element 250 pixels to the right."
},
{
"code": null,
"e": 2147,
"s": 2120,
"text": "$(\"div\").animate({: ''});\n"
},
{
"code": null,
"e": 2166,
"s": 2147,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2255,
"s": 2166,
"text": "For a complete overview of all jQuery effects, please go to our jQuery Effect Reference."
},
{
"code": null,
"e": 2288,
"s": 2255,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2330,
"s": 2288,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2437,
"s": 2330,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2456,
"s": 2437,
"text": "[email protected]"
}
]
|
Polynomial Regression for Non-Linear Data - ML - GeeksforGeeks | 03 Jun, 2020
Non-linear data is usually encountered in daily life. Consider some of the equations of motion as studied in physics.
Projectile Motion: The height of a projectile is calculated as h = -1⁄2 gt2 +ut +ho
Equation of motion under free fall: The distance travelled by an object after falling freely under gravity for ‘t’ seconds is 1⁄2 g t2.
Distance travelled by a uniformly accelerated body: The distance can be calculated as ut + 1⁄2at2where,g = acceleration due to gravityu = initial velocityho = initial heighta = acceleration
g = acceleration due to gravityu = initial velocityho = initial heighta = acceleration
In addition to these examples, Non-linear trends are also observed in the growth rate of tissues, the progress of disease epidemic, black body radiation, the motion of the pendulum etc. These examples clearly indicate that we cannot always have a linear relationship between the independent and dependent attributes. Hence, linear regression is a poor choice for dealing with such nonlinear situations. This is where Polynomial Regression comes to our rescue!!
Polynomial Regression is a powerful technique to encounter the situations where a quadratic, cubic or a higher degree nonlinear relationship exists. The underlying concept in polynomial regression is to add powers of each independent attribute as new attributes and then train a linear model on this expanded collection of features.Let us illustrate the use of Polynomial Regression with an example. Consider a situation where the dependent variable y varies with respect to an independent variable x following a relation
y = 13x2 + 2x + 7
.
We shall use Scikit-Learn’s PolynomialFeatures class for the implementation.
Step1: Import the libraries and generate a random dataset.
# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.metrics import mean_squared_error, r2_score # Importing the dataset## x = data, y = quadratic equationx = np.array(7 * np.random.rand(100, 1) - 3)x1 = x.reshape(-1, 1)y = 13 * x*x + 2 * x + 7
Step2: Plot the data points.
# data pointsplt.scatter(x, y, s = 10)plt.xlabel('x')plt.ylabel('y')plt.title('Non Linear Data')
Step3: First try to fit the data with a linear model.
# Model initializationregression_model = LinearRegression()# Fit the data(train the model)regression_model.fit(x1, y)print('Slope of the line is', regression_model.coef_)print('Intercept value is', regression_model.intercept_)# Predicty_predicted = regression_model.predict(x1)
Output:
Slope of the line is [[14.87780012]]
Intercept value is [58.31165769]
Step 4: Plot the data points and the linear line.
# data pointsplt.scatter(x, y, s = 10)plt.xlabel("$x$", fontsize = 18)plt.ylabel("$y$", rotation = 0, fontsize = 18)plt.title("data points") # predicted valuesplt.plot(x, y_predicted, color ='g')
Output:
Equation of the linear model is y = 14.87x + 58.31
Step 5: Calculate the performance of the model in terms of mean square error, root mean square error and r2 score.
# model evaluationmse = mean_squared_error(y, y_predicted) rmse = np.sqrt(mean_squared_error(y, y_predicted))r2 = r2_score(y, y_predicted) # printing values print('MSE of Linear model', mse) print('R2 score of Linear model: ', r2)
Output:
MSE of Linear model 2144.8229656677095
R2 score of Linear model: 0.3019970606151057
The performance of the linear model is not satisfactory. Let’s try Polynomial Regression with degree 2
Step 6: For improving the performance, we need to make the model a bit complex. So, lets fit a polynomial of degree 2 and proceed with linear regression.
poly_features = PolynomialFeatures(degree = 2, include_bias = False)x_poly = poly_features.fit_transform(x1)x[3]
Output:
Out[]:array([-2.84314447])
x_poly[3]
Output:
Out[]:array([-2.84314447, 8.08347046])
In addition to column x, one more column has been introduced which is the square of actual data. Now we proceed with simple Linear Regression
lin_reg = LinearRegression()lin_reg.fit(x_poly, y)print('Coefficients of x are', lin_reg.coef_)print('Intercept is', lin_reg.intercept_)
Output:
Coefficients of x are [[ 2. 13.]]
Intercept is [7.]
This is the desired equation 13x2 + 2x + 7
Step 7: Plot the quadratic equation obtained.
x_new = np.linspace(-3, 4, 100).reshape(100, 1)x_new_poly = poly_features.transform(x_new)y_new = lin_reg.predict(x_new_poly)plt.plot(x, y, "b.")plt.plot(x_new, y_new, "r-", linewidth = 2, label ="Predictions")plt.xlabel("$x_1$", fontsize = 18)plt.ylabel("$y$", rotation = 0, fontsize = 18)plt.legend(loc ="upper left", fontsize = 14) plt.title("Quadratic_predictions_plot")plt.show()
Output:
Step 8: Calculate the performance of the model obtained by Polynomial Regression.
y_deg2 = lin_reg.predict(x_poly)# model evaluationmse_deg2 = mean_squared_error(y, y_deg2) r2_deg2 = r2_score(y, y_deg2) # printing values print('MSE of Polyregression model', mse_deg2) print('R2 score of Linear model: ', r2_deg2)
Output:
MSE of Polyregression model 7.668437973562934e-28
R2 score of Linear model: 1.0
The performance of polynomial regression model is far better than linear regression model for the given quadratic equation.Important Facts: PolynomialFeatures (degree = d) transforms an array containing n features into an array containing (n + d)! / d! n! features.
Conclusion: Polynomial Regression is an effective way to deal with nonlinear data as it can find relationships between features which plain Linear Regression model struggles to do.
ML-Regression
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24778,
"s": 24750,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 24896,
"s": 24778,
"text": "Non-linear data is usually encountered in daily life. Consider some of the equations of motion as studied in physics."
},
{
"code": null,
"e": 24980,
"s": 24896,
"text": "Projectile Motion: The height of a projectile is calculated as h = -1⁄2 gt2 +ut +ho"
},
{
"code": null,
"e": 25116,
"s": 24980,
"text": "Equation of motion under free fall: The distance travelled by an object after falling freely under gravity for ‘t’ seconds is 1⁄2 g t2."
},
{
"code": null,
"e": 25306,
"s": 25116,
"text": "Distance travelled by a uniformly accelerated body: The distance can be calculated as ut + 1⁄2at2where,g = acceleration due to gravityu = initial velocityho = initial heighta = acceleration"
},
{
"code": null,
"e": 25393,
"s": 25306,
"text": "g = acceleration due to gravityu = initial velocityho = initial heighta = acceleration"
},
{
"code": null,
"e": 25854,
"s": 25393,
"text": "In addition to these examples, Non-linear trends are also observed in the growth rate of tissues, the progress of disease epidemic, black body radiation, the motion of the pendulum etc. These examples clearly indicate that we cannot always have a linear relationship between the independent and dependent attributes. Hence, linear regression is a poor choice for dealing with such nonlinear situations. This is where Polynomial Regression comes to our rescue!!"
},
{
"code": null,
"e": 26376,
"s": 25854,
"text": "Polynomial Regression is a powerful technique to encounter the situations where a quadratic, cubic or a higher degree nonlinear relationship exists. The underlying concept in polynomial regression is to add powers of each independent attribute as new attributes and then train a linear model on this expanded collection of features.Let us illustrate the use of Polynomial Regression with an example. Consider a situation where the dependent variable y varies with respect to an independent variable x following a relation"
},
{
"code": null,
"e": 26394,
"s": 26376,
"text": "y = 13x2 + 2x + 7"
},
{
"code": null,
"e": 26396,
"s": 26394,
"text": "."
},
{
"code": null,
"e": 26473,
"s": 26396,
"text": "We shall use Scikit-Learn’s PolynomialFeatures class for the implementation."
},
{
"code": null,
"e": 26532,
"s": 26473,
"text": "Step1: Import the libraries and generate a random dataset."
},
{
"code": "# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.metrics import mean_squared_error, r2_score # Importing the dataset## x = data, y = quadratic equationx = np.array(7 * np.random.rand(100, 1) - 3)x1 = x.reshape(-1, 1)y = 13 * x*x + 2 * x + 7 ",
"e": 26914,
"s": 26532,
"text": null
},
{
"code": null,
"e": 26943,
"s": 26914,
"text": "Step2: Plot the data points."
},
{
"code": "# data pointsplt.scatter(x, y, s = 10)plt.xlabel('x')plt.ylabel('y')plt.title('Non Linear Data')",
"e": 27040,
"s": 26943,
"text": null
},
{
"code": null,
"e": 27095,
"s": 27040,
"text": " Step3: First try to fit the data with a linear model."
},
{
"code": "# Model initializationregression_model = LinearRegression()# Fit the data(train the model)regression_model.fit(x1, y)print('Slope of the line is', regression_model.coef_)print('Intercept value is', regression_model.intercept_)# Predicty_predicted = regression_model.predict(x1)",
"e": 27373,
"s": 27095,
"text": null
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Output:"
},
{
"code": null,
"e": 27452,
"s": 27381,
"text": "Slope of the line is [[14.87780012]]\nIntercept value is [58.31165769]\n"
},
{
"code": null,
"e": 27502,
"s": 27452,
"text": "Step 4: Plot the data points and the linear line."
},
{
"code": "# data pointsplt.scatter(x, y, s = 10)plt.xlabel(\"$x$\", fontsize = 18)plt.ylabel(\"$y$\", rotation = 0, fontsize = 18)plt.title(\"data points\") # predicted valuesplt.plot(x, y_predicted, color ='g')",
"e": 27699,
"s": 27502,
"text": null
},
{
"code": null,
"e": 27707,
"s": 27699,
"text": "Output:"
},
{
"code": null,
"e": 27759,
"s": 27707,
"text": "Equation of the linear model is y = 14.87x + 58.31\n"
},
{
"code": null,
"e": 27876,
"s": 27761,
"text": "Step 5: Calculate the performance of the model in terms of mean square error, root mean square error and r2 score."
},
{
"code": "# model evaluationmse = mean_squared_error(y, y_predicted) rmse = np.sqrt(mean_squared_error(y, y_predicted))r2 = r2_score(y, y_predicted) # printing values print('MSE of Linear model', mse) print('R2 score of Linear model: ', r2)",
"e": 28111,
"s": 27876,
"text": null
},
{
"code": null,
"e": 28119,
"s": 28111,
"text": "Output:"
},
{
"code": null,
"e": 28205,
"s": 28119,
"text": "MSE of Linear model 2144.8229656677095\nR2 score of Linear model: 0.3019970606151057\n"
},
{
"code": null,
"e": 28308,
"s": 28205,
"text": "The performance of the linear model is not satisfactory. Let’s try Polynomial Regression with degree 2"
},
{
"code": null,
"e": 28462,
"s": 28308,
"text": "Step 6: For improving the performance, we need to make the model a bit complex. So, lets fit a polynomial of degree 2 and proceed with linear regression."
},
{
"code": "poly_features = PolynomialFeatures(degree = 2, include_bias = False)x_poly = poly_features.fit_transform(x1)x[3]",
"e": 28575,
"s": 28462,
"text": null
},
{
"code": null,
"e": 28583,
"s": 28575,
"text": "Output:"
},
{
"code": null,
"e": 28610,
"s": 28583,
"text": "Out[]:array([-2.84314447])"
},
{
"code": "x_poly[3]",
"e": 28620,
"s": 28610,
"text": null
},
{
"code": null,
"e": 28628,
"s": 28620,
"text": "Output:"
},
{
"code": null,
"e": 28671,
"s": 28628,
"text": " Out[]:array([-2.84314447, 8.08347046])\n"
},
{
"code": null,
"e": 28813,
"s": 28671,
"text": "In addition to column x, one more column has been introduced which is the square of actual data. Now we proceed with simple Linear Regression"
},
{
"code": "lin_reg = LinearRegression()lin_reg.fit(x_poly, y)print('Coefficients of x are', lin_reg.coef_)print('Intercept is', lin_reg.intercept_)",
"e": 28950,
"s": 28813,
"text": null
},
{
"code": null,
"e": 28958,
"s": 28950,
"text": "Output:"
},
{
"code": null,
"e": 29011,
"s": 28958,
"text": "Coefficients of x are [[ 2. 13.]]\nIntercept is [7.]\n"
},
{
"code": null,
"e": 29054,
"s": 29011,
"text": "This is the desired equation 13x2 + 2x + 7"
},
{
"code": null,
"e": 29100,
"s": 29054,
"text": "Step 7: Plot the quadratic equation obtained."
},
{
"code": "x_new = np.linspace(-3, 4, 100).reshape(100, 1)x_new_poly = poly_features.transform(x_new)y_new = lin_reg.predict(x_new_poly)plt.plot(x, y, \"b.\")plt.plot(x_new, y_new, \"r-\", linewidth = 2, label =\"Predictions\")plt.xlabel(\"$x_1$\", fontsize = 18)plt.ylabel(\"$y$\", rotation = 0, fontsize = 18)plt.legend(loc =\"upper left\", fontsize = 14) plt.title(\"Quadratic_predictions_plot\")plt.show()",
"e": 29486,
"s": 29100,
"text": null
},
{
"code": null,
"e": 29495,
"s": 29486,
"text": "Output: "
},
{
"code": null,
"e": 29577,
"s": 29495,
"text": "Step 8: Calculate the performance of the model obtained by Polynomial Regression."
},
{
"code": "y_deg2 = lin_reg.predict(x_poly)# model evaluationmse_deg2 = mean_squared_error(y, y_deg2) r2_deg2 = r2_score(y, y_deg2) # printing values print('MSE of Polyregression model', mse_deg2) print('R2 score of Linear model: ', r2_deg2)",
"e": 29812,
"s": 29577,
"text": null
},
{
"code": null,
"e": 29820,
"s": 29812,
"text": "Output:"
},
{
"code": null,
"e": 29902,
"s": 29820,
"text": "MSE of Polyregression model 7.668437973562934e-28\nR2 score of Linear model: 1.0\n"
},
{
"code": null,
"e": 30168,
"s": 29902,
"text": "The performance of polynomial regression model is far better than linear regression model for the given quadratic equation.Important Facts: PolynomialFeatures (degree = d) transforms an array containing n features into an array containing (n + d)! / d! n! features."
},
{
"code": null,
"e": 30349,
"s": 30168,
"text": "Conclusion: Polynomial Regression is an effective way to deal with nonlinear data as it can find relationships between features which plain Linear Regression model struggles to do."
},
{
"code": null,
"e": 30363,
"s": 30349,
"text": "ML-Regression"
},
{
"code": null,
"e": 30380,
"s": 30363,
"text": "Machine Learning"
},
{
"code": null,
"e": 30387,
"s": 30380,
"text": "Python"
},
{
"code": null,
"e": 30404,
"s": 30387,
"text": "Machine Learning"
},
{
"code": null,
"e": 30502,
"s": 30404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30516,
"s": 30502,
"text": "Decision Tree"
},
{
"code": null,
"e": 30554,
"s": 30516,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 30578,
"s": 30554,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 30618,
"s": 30578,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 30641,
"s": 30618,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 30669,
"s": 30641,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30719,
"s": 30669,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30741,
"s": 30719,
"text": "Python map() function"
}
]
|
NULL pointer in C | A null pointer is a pointer which points nothing.
Some uses of the null pointer are:
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
b) To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
c) To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
Begin.
Declare a pointer p of the integer datatype.
Initialize *p= NULL.
Print “The value of pointer is”.
Print the value of the pointer p.
End.
Live Demo
#include <stdio.h>
int main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p);
return 0;
}
The value of pointer is 0. | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "A null pointer is a pointer which points nothing."
},
{
"code": null,
"e": 1147,
"s": 1112,
"text": "Some uses of the null pointer are:"
},
{
"code": null,
"e": 1255,
"s": 1147,
"text": "a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet."
},
{
"code": null,
"e": 1357,
"s": 1255,
"text": "b) To pass a null pointer to a function argument when we don’t want to pass any valid memory address."
},
{
"code": null,
"e": 1545,
"s": 1357,
"text": "c) To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL."
},
{
"code": null,
"e": 1708,
"s": 1545,
"text": "Begin.\n Declare a pointer p of the integer datatype.\n Initialize *p= NULL.\n Print “The value of pointer is”.\n Print the value of the pointer p.\nEnd."
},
{
"code": null,
"e": 1719,
"s": 1708,
"text": " Live Demo"
},
{
"code": null,
"e": 1859,
"s": 1719,
"text": "#include <stdio.h>\nint main() {\n int *p= NULL;//initialize the pointer as null.\n printf(\"The value of pointer is %u\",p);\n return 0;\n}"
},
{
"code": null,
"e": 1886,
"s": 1859,
"text": "The value of pointer is 0."
}
]
|
Check if a number is a Krishnamurthy Number or not - GeeksforGeeks | 07 Apr, 2021
A Krishnamurthy number is a number whose sum of the factorial of digits is equal to the number itself. For example 145, sum of factorial of each digits: 1! + 4! + 5! = 1 + 24 + 120 = 145
Examples:
Input : 145
Output : YES
Explanation: 1! + 4! + 5! =
1 + 24 + 120 = 145, which is equal to input,
hence YES.
Input : 235
Output : NO
Explanation: 2! + 3! + 5! =
2 + 6 + 120 = 128, which is not equal to input,
hence NO.
The idea is simple, we compute sum of factorials of all digits and then compare the sum with n.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number// is a krishnamurthy number#include <bits/stdc++.h>using namespace std; // Function to calculate the factorial of any numberint factorial(int n){ int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact;} // function to Check if number is krishnamurthybool isKrishnamurthy(int n){ int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of last digit // of temp and add it to sum sum += factorial(temp % 10); // replace value of temp by temp/10 temp = temp / 10; } // Check if number is krishnamurthy return (sum == n);} // Driver codeint main(){ int n = 145; if (isKrishnamurthy(n)) cout << "YES"; else cout << "NO"; return 0;}
// Java program to check if a number// is a krishnamurthy number.import java.util.*;import java.io.*; class Krishnamurthy { // function to calculate the factorial // of any number static int factorial(int n) { int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact; } // function to Check if number is krishnamurthy static boolean isKrishnamurthy(int n) { int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of last digit // of temp and add it to sum sum += factorial(temp % 10); // replace value of temp by temp/10 temp = temp / 10; } // Check if number is krishnamurthy return (sum == n); } // Driver code public static void main(String[] args) { int n = 145; if (isKrishnamurthy(n)) System.out.println("YES"); else System.out.println("NO"); }}
# Python program to check if a number# is a krishnamurthy number # function to calculate the factorial# of any numberdef factorial(n) : fact = 1 while (n != 0) : fact = fact * n n = n - 1 return fact # function to Check if number is# krishnamurthy/specialdef isKrishnamurthy(n) : sum = 0 temp = n while (temp != 0) : # calculate factorial of last digit # of temp and add it to sum rem = temp%10 sum = sum + factorial(rem) # replace value of temp by temp / 10 temp = temp // 10 # Check if number is krishnamurthy return (sum == n) # Driver coden = 145if (isKrishnamurthy(n)) : print("YES")else : print("NO") # This code is contributed by Prashant Aggarwal
// C# program to check if a number// is a krishnamurthy number.using System; class GFG { // function to calculate the // factorial of any number static int factorial(int n) { int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact; } // function to Check if number is // krishnamurthy static bool isKrishnamurthy(int n) { int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of // last digit of temp and // add it to sum sum += factorial(temp % 10); // replace value of temp // by temp/10 temp = temp / 10; } // Check if number is // krishnamurthy return (sum == n); } // Driver code public static void Main() { int n = 145; if (isKrishnamurthy(n)) Console.Write("YES"); else Console.Write("NO"); }} // This code is contributed by nitin mittal.
<?php// PHP program to check if a number// is a krishnamurthy number // Function to find Factorial// of any numberfunction factorial($n){ $fact = 1; while($n != 0) { $fact = $fact * $n; $n--; } return $fact;} // function to Check if number// is krishnamurthyfunction isKrishnamurthyNumber($n){ $sum = 0; // Storing the value in // other variable $temp = $n; while($temp != 0) { // calculate factorial of last digit // of temp and add it to sum $sum = $sum + factorial($temp % 10); // Integer Division // replace value of temp by temp/10 $temp = intdiv($temp, 10); } // Check if number is krishnamurthy return $sum == $n;} // Driver code$n = 145; if (isKrishnamurthyNumber($n)) echo "YES";else echo "NO"; // This code is contributed by akash7981?>
<script> // Javascript program to check if a number// is a krishnamurthy number // Function to find Factorial// of any numberfunction factorial(n){ let fact = 1; while (n != 0) { fact = fact * n; n--; } return fact;} // Function to check if number// is krishnamurthyfunction isKrishnamurthyNumber(n){ let sum = 0; // Storing the value in // other variable let temp = n; while (temp != 0) { // Calculate factorial of last digit // of temp and add it to sum sum = sum + factorial(temp % 10); // Integer Division // replace value of temp by temp/10 temp = parseInt(temp / 10); } // Check if number is krishnamurthy return sum == n;} // Driver codelet n = 145; if (isKrishnamurthyNumber(n)) document.write("YES");else document.write("NO"); // This code is contributed by _saurabh_jaiswal </script>
Output:
YES
Interestingly, there are exactly four Krishnamurthy numbers i.e. 1, 2, 145, and 40585 known to us.
YouTubeGeeksforGeeks501K subscribersKrishnamurthy Numbers | 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 / 5:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=U5jJkZYG0dQ" 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 DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
prshntaggrwl
_saurabh_jaiswal
factorial
Mathematical
School Programming
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Modular multiplicative inverse
Program to multiply two matrices
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 24903,
"s": 24716,
"text": "A Krishnamurthy number is a number whose sum of the factorial of digits is equal to the number itself. For example 145, sum of factorial of each digits: 1! + 4! + 5! = 1 + 24 + 120 = 145"
},
{
"code": null,
"e": 24914,
"s": 24903,
"text": "Examples: "
},
{
"code": null,
"e": 25137,
"s": 24914,
"text": "Input : 145\nOutput : YES\nExplanation: 1! + 4! + 5! = \n1 + 24 + 120 = 145, which is equal to input,\nhence YES.\n\nInput : 235\nOutput : NO\nExplanation: 2! + 3! + 5! = \n2 + 6 + 120 = 128, which is not equal to input, \nhence NO."
},
{
"code": null,
"e": 25234,
"s": 25137,
"text": "The idea is simple, we compute sum of factorials of all digits and then compare the sum with n. "
},
{
"code": null,
"e": 25238,
"s": 25234,
"text": "C++"
},
{
"code": null,
"e": 25243,
"s": 25238,
"text": "Java"
},
{
"code": null,
"e": 25251,
"s": 25243,
"text": "Python3"
},
{
"code": null,
"e": 25254,
"s": 25251,
"text": "C#"
},
{
"code": null,
"e": 25258,
"s": 25254,
"text": "PHP"
},
{
"code": null,
"e": 25269,
"s": 25258,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number// is a krishnamurthy number#include <bits/stdc++.h>using namespace std; // Function to calculate the factorial of any numberint factorial(int n){ int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact;} // function to Check if number is krishnamurthybool isKrishnamurthy(int n){ int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of last digit // of temp and add it to sum sum += factorial(temp % 10); // replace value of temp by temp/10 temp = temp / 10; } // Check if number is krishnamurthy return (sum == n);} // Driver codeint main(){ int n = 145; if (isKrishnamurthy(n)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 26066,
"s": 25269,
"text": null
},
{
"code": "// Java program to check if a number// is a krishnamurthy number.import java.util.*;import java.io.*; class Krishnamurthy { // function to calculate the factorial // of any number static int factorial(int n) { int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact; } // function to Check if number is krishnamurthy static boolean isKrishnamurthy(int n) { int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of last digit // of temp and add it to sum sum += factorial(temp % 10); // replace value of temp by temp/10 temp = temp / 10; } // Check if number is krishnamurthy return (sum == n); } // Driver code public static void main(String[] args) { int n = 145; if (isKrishnamurthy(n)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}",
"e": 27077,
"s": 26066,
"text": null
},
{
"code": "# Python program to check if a number# is a krishnamurthy number # function to calculate the factorial# of any numberdef factorial(n) : fact = 1 while (n != 0) : fact = fact * n n = n - 1 return fact # function to Check if number is# krishnamurthy/specialdef isKrishnamurthy(n) : sum = 0 temp = n while (temp != 0) : # calculate factorial of last digit # of temp and add it to sum rem = temp%10 sum = sum + factorial(rem) # replace value of temp by temp / 10 temp = temp // 10 # Check if number is krishnamurthy return (sum == n) # Driver coden = 145if (isKrishnamurthy(n)) : print(\"YES\")else : print(\"NO\") # This code is contributed by Prashant Aggarwal",
"e": 27830,
"s": 27077,
"text": null
},
{
"code": "// C# program to check if a number// is a krishnamurthy number.using System; class GFG { // function to calculate the // factorial of any number static int factorial(int n) { int fact = 1; while (n != 0) { fact = fact * n; n--; } return fact; } // function to Check if number is // krishnamurthy static bool isKrishnamurthy(int n) { int sum = 0; int temp = n; while (temp != 0) { // calculate factorial of // last digit of temp and // add it to sum sum += factorial(temp % 10); // replace value of temp // by temp/10 temp = temp / 10; } // Check if number is // krishnamurthy return (sum == n); } // Driver code public static void Main() { int n = 145; if (isKrishnamurthy(n)) Console.Write(\"YES\"); else Console.Write(\"NO\"); }} // This code is contributed by nitin mittal.",
"e": 28905,
"s": 27830,
"text": null
},
{
"code": "<?php// PHP program to check if a number// is a krishnamurthy number // Function to find Factorial// of any numberfunction factorial($n){ $fact = 1; while($n != 0) { $fact = $fact * $n; $n--; } return $fact;} // function to Check if number// is krishnamurthyfunction isKrishnamurthyNumber($n){ $sum = 0; // Storing the value in // other variable $temp = $n; while($temp != 0) { // calculate factorial of last digit // of temp and add it to sum $sum = $sum + factorial($temp % 10); // Integer Division // replace value of temp by temp/10 $temp = intdiv($temp, 10); } // Check if number is krishnamurthy return $sum == $n;} // Driver code$n = 145; if (isKrishnamurthyNumber($n)) echo \"YES\";else echo \"NO\"; // This code is contributed by akash7981?>",
"e": 29786,
"s": 28905,
"text": null
},
{
"code": "<script> // Javascript program to check if a number// is a krishnamurthy number // Function to find Factorial// of any numberfunction factorial(n){ let fact = 1; while (n != 0) { fact = fact * n; n--; } return fact;} // Function to check if number// is krishnamurthyfunction isKrishnamurthyNumber(n){ let sum = 0; // Storing the value in // other variable let temp = n; while (temp != 0) { // Calculate factorial of last digit // of temp and add it to sum sum = sum + factorial(temp % 10); // Integer Division // replace value of temp by temp/10 temp = parseInt(temp / 10); } // Check if number is krishnamurthy return sum == n;} // Driver codelet n = 145; if (isKrishnamurthyNumber(n)) document.write(\"YES\");else document.write(\"NO\"); // This code is contributed by _saurabh_jaiswal </script>",
"e": 30731,
"s": 29786,
"text": null
},
{
"code": null,
"e": 30740,
"s": 30731,
"text": "Output: "
},
{
"code": null,
"e": 30744,
"s": 30740,
"text": "YES"
},
{
"code": null,
"e": 30845,
"s": 30744,
"text": "Interestingly, there are exactly four Krishnamurthy numbers i.e. 1, 2, 145, and 40585 known to us. "
},
{
"code": null,
"e": 31665,
"s": 30845,
"text": "YouTubeGeeksforGeeks501K subscribersKrishnamurthy Numbers | 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 / 5:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=U5jJkZYG0dQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 32087,
"s": 31665,
"text": "This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32100,
"s": 32087,
"text": "nitin mittal"
},
{
"code": null,
"e": 32113,
"s": 32100,
"text": "prshntaggrwl"
},
{
"code": null,
"e": 32130,
"s": 32113,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32140,
"s": 32130,
"text": "factorial"
},
{
"code": null,
"e": 32153,
"s": 32140,
"text": "Mathematical"
},
{
"code": null,
"e": 32172,
"s": 32153,
"text": "School Programming"
},
{
"code": null,
"e": 32185,
"s": 32172,
"text": "Mathematical"
},
{
"code": null,
"e": 32195,
"s": 32185,
"text": "factorial"
},
{
"code": null,
"e": 32293,
"s": 32195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32302,
"s": 32293,
"text": "Comments"
},
{
"code": null,
"e": 32315,
"s": 32302,
"text": "Old Comments"
},
{
"code": null,
"e": 32347,
"s": 32315,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 32391,
"s": 32347,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32416,
"s": 32391,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32447,
"s": 32416,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32480,
"s": 32447,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32498,
"s": 32480,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32514,
"s": 32498,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32533,
"s": 32514,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32558,
"s": 32533,
"text": "Reverse a string in Java"
}
]
|
Git GitHub Send Pull Request | We have made a lot of changes to our local Git.
Now we push them to our GitHub
fork:
commit the changes:
git push origin
Enumerating objects: 8, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 16 threads
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 393.96 KiB | 32.83 MiB/s, done.
Total 5 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/kaijim/w3schools-test.github.io.git
facaeae..ebb1a5c master -> master
Go to GitHub, and we see that the repository has a new commit. And we can send a Pull Request to the original repository:
Click that and create a pull request:
Remember to add an explanation for the administrators.
Pull Request is sent:
Now any member with access can see the Pull Request when they see the original repository:
And they can see the proposed changes:
Comment on the changes and merge:
Confirm:
And changes have been merged with
master:
Now you try!
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 48,
"s": 0,
"text": "We have made a lot of changes to our local Git."
},
{
"code": null,
"e": 86,
"s": 48,
"text": "Now we push them to our GitHub \nfork:"
},
{
"code": null,
"e": 106,
"s": 86,
"text": "commit the changes:"
},
{
"code": null,
"e": 478,
"s": 106,
"text": "git push origin\nEnumerating objects: 8, done.\nCounting objects: 100% (8/8), done.\nDelta compression using up to 16 threads\nCompressing objects: 100% (5/5), done.\nWriting objects: 100% (5/5), 393.96 KiB | 32.83 MiB/s, done.\nTotal 5 (delta 0), reused 0 (delta 0), pack-reused 0\nTo https://github.com/kaijim/w3schools-test.github.io.git\n facaeae..ebb1a5c master -> master"
},
{
"code": null,
"e": 600,
"s": 478,
"text": "Go to GitHub, and we see that the repository has a new commit. And we can send a Pull Request to the original repository:"
},
{
"code": null,
"e": 638,
"s": 600,
"text": "Click that and create a pull request:"
},
{
"code": null,
"e": 693,
"s": 638,
"text": "Remember to add an explanation for the administrators."
},
{
"code": null,
"e": 715,
"s": 693,
"text": "Pull Request is sent:"
},
{
"code": null,
"e": 806,
"s": 715,
"text": "Now any member with access can see the Pull Request when they see the original repository:"
},
{
"code": null,
"e": 845,
"s": 806,
"text": "And they can see the proposed changes:"
},
{
"code": null,
"e": 879,
"s": 845,
"text": "Comment on the changes and merge:"
},
{
"code": null,
"e": 888,
"s": 879,
"text": "Confirm:"
},
{
"code": null,
"e": 931,
"s": 888,
"text": "And changes have been merged with \nmaster:"
},
{
"code": null,
"e": 944,
"s": 931,
"text": "Now you try!"
},
{
"code": null,
"e": 977,
"s": 944,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1019,
"s": 977,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1126,
"s": 1019,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1145,
"s": 1126,
"text": "[email protected]"
}
]
|
Rearrange an array in maximum minimum form | Set 1 | 30 Jun, 2022
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be maximum value, second minimum value, third second max, fourth second min and so on.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}
Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3}
Expected time complexity: O(n).
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The idea is to use an auxiliary array. We maintain two pointers one to leftmost or smallest element and other to rightmost or largest element. We move both pointers toward each other and alternatively copy elements at these pointers to an auxiliary array. Finally, we copy the auxiliary array back to the original array.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to rearrange an array in minimum// maximum form#include <bits/stdc++.h>using namespace std; // Prints max at first position, min at second position// second max at third position, second min at fourth// position and so on.void rearrange(int arr[], int n){ // Auxiliary array to hold modified array int temp[n]; // Indexes of smallest and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position int flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original Array\n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; rearrange(arr, n); cout << "\nModified Array\n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
// Java program to rearrange an array in minimum// maximum form import java.util.Arrays; public class GFG{ // Prints max at first position, min at second position // second max at third position, second min at fourth // position and so on. static void rearrange(int[] arr, int n) { // Auxiliary array to hold modified array int temp[] = arr.clone(); // Indexes of smallest and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position boolean flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) arr[i] = temp[large--]; else arr[i] = temp[small++]; flag = !flag; } } // Driver code public static void main(String[] args) { int arr[] = new int[] { 1, 2, 3, 4, 5, 6 }; System.out.println("Original Array "); System.out.println(Arrays.toString(arr)); rearrange(arr, arr.length); System.out.println("Modified Array "); System.out.println(Arrays.toString(arr)); }}
# Python program to rearrange an array in minimum# maximum form # Prints max at first position, min at second position# second max at third position, second min at fourth# position and so on. def rearrange(arr, n): # Auxiliary array to hold modified array temp = n*[None] # Indexes of smallest and largest elements # from remaining array. small, large = 0, n-1 # To indicate whether we need to copy remaining # largest or remaining smallest at next position flag = True # Store result in temp[] for i in range(n): if flag is True: temp[i] = arr[large] large -= 1 else: temp[i] = arr[small] small += 1 flag = bool(1-flag) # Copy temp[] to arr[] for i in range(n): arr[i] = temp[i] return arr # Driver codearr = [1, 2, 3, 4, 5, 6]n = len(arr)print("Original Array")print(arr)print("Modified Array")print(rearrange(arr, n)) # This code is contributed by Pratik Chhajer
// C# program to rearrange// an array in minimum// maximum formusing System; class GFG { // Prints max at first position, // min at second position second // max at third position, second // min at fourth position and so on. static void rearrange(int[] arr, int n) { // Auxiliary array to // hold modified array int[] temp = new int[n]; // Indexes of smallest // and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we // need to copy remaining // largest or remaining // smallest at next position bool flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver Code static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; Console.WriteLine("Original Array"); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); rearrange(arr, arr.Length); Console.WriteLine("\nModified Array"); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); }} // This code is contributed// by Sam007
<?php// PHP program to rearrange an array in// minimum-maximum form // Prints max at first position, min at// second position second max at third// position, second min at fourth// position and so on.function rearrange(&$arr, $n){ // Auxiliary array to hold modified array $temp = array(); // Indexes of smallest and largest elements // from remaining array. $small = 0; $large = $n - 1; // To indicate whether we need to copy // remaining largest or remaining smallest // at next position $flag = true; // Store result in temp[] for ($i = 0; $i < $n; $i++) { if ($flag) $temp[$i] = $arr[$large--]; else $temp[$i] = $arr[$small++]; $flag = !$flag; } // Copy temp[] to arr[] for ($i = 0; $i < $n; $i++) $arr[$i] = $temp[$i];} // Driver Code$arr = array(1, 2, 3, 4, 5, 6);$n = count($arr); echo "Original Arrayn\n";for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; rearrange($arr, $n); echo "\nModified Arrayn\n";for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; // This code is contributed by// Rajput-Ji?>
<script> // JavaScript program to rearrange an array in minimum// maximum form // Prints max at first position, min at second position// second max at third position, second min at fourth// position and so on.function rearrange(arr, n){ // Auxiliary array to hold modified array let temp = new Array(n); // Indexes of smallest and largest elements // from remaining array. let small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position let flag = true; // Store result in temp[] for (let i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (let i = 0; i < n; i++) arr[i] = temp[i];} // Driver code let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; document.write("Original Array<br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); rearrange(arr, n); document.write("<br>Modified Array<br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi. </script>
Original Array
1 2 3 4 5 6
Modified Array
6 1 5 2 4 3
Time Complexity: O(n) Auxiliary Space: O(n)
Exercise: How to solve this problem if extra space is not allowed? Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)
Sam007
Rajput-Ji
ramanshhrma
13manujchaturvedi
surbhityagi15
simmytarika5
gulshankumarar231
amartyaghoshgfg
hardikkoriintern
Zoho
Arrays
Sorting
Zoho
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 242,
"s": 54,
"text": "Given a sorted array of positive integers, rearrange the array alternately i.e first element should be maximum value, second minimum value, third second max, fourth second min and so on. "
},
{
"code": null,
"e": 253,
"s": 242,
"text": "Examples: "
},
{
"code": null,
"e": 328,
"s": 253,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}"
},
{
"code": null,
"e": 398,
"s": 328,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3} "
},
{
"code": null,
"e": 430,
"s": 398,
"text": "Expected time complexity: O(n)."
},
{
"code": null,
"e": 439,
"s": 430,
"text": "Chapters"
},
{
"code": null,
"e": 466,
"s": 439,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 516,
"s": 466,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 539,
"s": 516,
"text": "captions off, selected"
},
{
"code": null,
"e": 547,
"s": 539,
"text": "English"
},
{
"code": null,
"e": 571,
"s": 547,
"text": "This is a modal window."
},
{
"code": null,
"e": 640,
"s": 571,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 662,
"s": 640,
"text": "End of dialog window."
},
{
"code": null,
"e": 983,
"s": 662,
"text": "The idea is to use an auxiliary array. We maintain two pointers one to leftmost or smallest element and other to rightmost or largest element. We move both pointers toward each other and alternatively copy elements at these pointers to an auxiliary array. Finally, we copy the auxiliary array back to the original array."
},
{
"code": null,
"e": 1033,
"s": 983,
"text": "Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 1084,
"s": 1033,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1088,
"s": 1084,
"text": "C++"
},
{
"code": null,
"e": 1093,
"s": 1088,
"text": "Java"
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Python3"
},
{
"code": null,
"e": 1104,
"s": 1101,
"text": "C#"
},
{
"code": null,
"e": 1108,
"s": 1104,
"text": "PHP"
},
{
"code": null,
"e": 1119,
"s": 1108,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange an array in minimum// maximum form#include <bits/stdc++.h>using namespace std; // Prints max at first position, min at second position// second max at third position, second min at fourth// position and so on.void rearrange(int arr[], int n){ // Auxiliary array to hold modified array int temp[n]; // Indexes of smallest and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position int flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Original Array\\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; rearrange(arr, n); cout << \"\\nModified Array\\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 2289,
"s": 1119,
"text": null
},
{
"code": "// Java program to rearrange an array in minimum// maximum form import java.util.Arrays; public class GFG{ // Prints max at first position, min at second position // second max at third position, second min at fourth // position and so on. static void rearrange(int[] arr, int n) { // Auxiliary array to hold modified array int temp[] = arr.clone(); // Indexes of smallest and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position boolean flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) arr[i] = temp[large--]; else arr[i] = temp[small++]; flag = !flag; } } // Driver code public static void main(String[] args) { int arr[] = new int[] { 1, 2, 3, 4, 5, 6 }; System.out.println(\"Original Array \"); System.out.println(Arrays.toString(arr)); rearrange(arr, arr.length); System.out.println(\"Modified Array \"); System.out.println(Arrays.toString(arr)); }}",
"e": 3508,
"s": 2289,
"text": null
},
{
"code": "# Python program to rearrange an array in minimum# maximum form # Prints max at first position, min at second position# second max at third position, second min at fourth# position and so on. def rearrange(arr, n): # Auxiliary array to hold modified array temp = n*[None] # Indexes of smallest and largest elements # from remaining array. small, large = 0, n-1 # To indicate whether we need to copy remaining # largest or remaining smallest at next position flag = True # Store result in temp[] for i in range(n): if flag is True: temp[i] = arr[large] large -= 1 else: temp[i] = arr[small] small += 1 flag = bool(1-flag) # Copy temp[] to arr[] for i in range(n): arr[i] = temp[i] return arr # Driver codearr = [1, 2, 3, 4, 5, 6]n = len(arr)print(\"Original Array\")print(arr)print(\"Modified Array\")print(rearrange(arr, n)) # This code is contributed by Pratik Chhajer",
"e": 4492,
"s": 3508,
"text": null
},
{
"code": "// C# program to rearrange// an array in minimum// maximum formusing System; class GFG { // Prints max at first position, // min at second position second // max at third position, second // min at fourth position and so on. static void rearrange(int[] arr, int n) { // Auxiliary array to // hold modified array int[] temp = new int[n]; // Indexes of smallest // and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we // need to copy remaining // largest or remaining // smallest at next position bool flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver Code static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; Console.WriteLine(\"Original Array\"); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + \" \"); rearrange(arr, arr.Length); Console.WriteLine(\"\\nModified Array\"); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed// by Sam007",
"e": 5910,
"s": 4492,
"text": null
},
{
"code": "<?php// PHP program to rearrange an array in// minimum-maximum form // Prints max at first position, min at// second position second max at third// position, second min at fourth// position and so on.function rearrange(&$arr, $n){ // Auxiliary array to hold modified array $temp = array(); // Indexes of smallest and largest elements // from remaining array. $small = 0; $large = $n - 1; // To indicate whether we need to copy // remaining largest or remaining smallest // at next position $flag = true; // Store result in temp[] for ($i = 0; $i < $n; $i++) { if ($flag) $temp[$i] = $arr[$large--]; else $temp[$i] = $arr[$small++]; $flag = !$flag; } // Copy temp[] to arr[] for ($i = 0; $i < $n; $i++) $arr[$i] = $temp[$i];} // Driver Code$arr = array(1, 2, 3, 4, 5, 6);$n = count($arr); echo \"Original Arrayn\\n\";for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; rearrange($arr, $n); echo \"\\nModified Arrayn\\n\";for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; // This code is contributed by// Rajput-Ji?>",
"e": 7027,
"s": 5910,
"text": null
},
{
"code": "<script> // JavaScript program to rearrange an array in minimum// maximum form // Prints max at first position, min at second position// second max at third position, second min at fourth// position and so on.function rearrange(arr, n){ // Auxiliary array to hold modified array let temp = new Array(n); // Indexes of smallest and largest elements // from remaining array. let small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position let flag = true; // Store result in temp[] for (let i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (let i = 0; i < n; i++) arr[i] = temp[i];} // Driver code let arr = [ 1, 2, 3, 4, 5, 6 ]; let n = arr.length; document.write(\"Original Array<br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); rearrange(arr, n); document.write(\"<br>Modified Array<br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 8221,
"s": 7027,
"text": null
},
{
"code": null,
"e": 8277,
"s": 8221,
"text": "Original Array\n1 2 3 4 5 6 \nModified Array\n6 1 5 2 4 3 "
},
{
"code": null,
"e": 8322,
"s": 8277,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 8459,
"s": 8322,
"text": "Exercise: How to solve this problem if extra space is not allowed? Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)"
},
{
"code": null,
"e": 8466,
"s": 8459,
"text": "Sam007"
},
{
"code": null,
"e": 8476,
"s": 8466,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8488,
"s": 8476,
"text": "ramanshhrma"
},
{
"code": null,
"e": 8506,
"s": 8488,
"text": "13manujchaturvedi"
},
{
"code": null,
"e": 8520,
"s": 8506,
"text": "surbhityagi15"
},
{
"code": null,
"e": 8533,
"s": 8520,
"text": "simmytarika5"
},
{
"code": null,
"e": 8551,
"s": 8533,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 8567,
"s": 8551,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 8584,
"s": 8567,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 8589,
"s": 8584,
"text": "Zoho"
},
{
"code": null,
"e": 8596,
"s": 8589,
"text": "Arrays"
},
{
"code": null,
"e": 8604,
"s": 8596,
"text": "Sorting"
},
{
"code": null,
"e": 8609,
"s": 8604,
"text": "Zoho"
},
{
"code": null,
"e": 8616,
"s": 8609,
"text": "Arrays"
},
{
"code": null,
"e": 8624,
"s": 8616,
"text": "Sorting"
}
]
|
How to create a list with roman number indexing in HTML ? | 18 Aug, 2021
In this article, We are going to create a list with roman number indexing. In HTML, A list is a record of short pieces of information, such as people’s names, usually written or printed with a single thing on each line and ordered in a way that makes a particular thing easy to find.
Approach: There are different types of lists in HTML. One of them is Ordered list or ol. Ordered list uses <ol> tag. To create an ordered list with roman number indexing we will use attribute type. The type attribute of the <ol> tag defines the numbering type of the list items. The default value of the type attribute in the ordered list is number. So for example, if we want the list with alphabets we simply give value “a” to type attribute. Similarly for creating a list with roman number indexing we have to provide the first roman number value to the type attribute.
Syntax:
<ol type="I">
Below is the implementation of the above approach.
Example 1: In this example, we will create a list with uppercase roman number indexing. For that, we will provide attribute type value to “I”.
HTML
<!DOCTYPE html><html> <head> <style> h2 { color: green; } </style></head> <body> <h2>Ordered List with Roman Numbers</h2> <ol type="I"> <li>HTML</li> <li>CSS</li> <li>JAVA</li> <li>SASS</li> </ol></body> </html>
Output:
GFG
Example 2: Now we will create a list with lowercase roman number indexing. The entire code will be the same as before we will just change the type attribute value from “I” to “i” now.
HTML
<!DOCTYPE html><html> <head> <style> h2 { color: green; } </style></head> <body> <h2> Ordered List with LowerCase Roman Numbers </h2> <ol type="i"> <li>HTML</li> <li>CSS</li> <li>JAVA</li> <li>SASS</li> </ol></body> </html>
Output:
GFG
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
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": "\n18 Aug, 2021"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "In this article, We are going to create a list with roman number indexing. In HTML, A list is a record of short pieces of information, such as people’s names, usually written or printed with a single thing on each line and ordered in a way that makes a particular thing easy to find. "
},
{
"code": null,
"e": 890,
"s": 313,
"text": "Approach: There are different types of lists in HTML. One of them is Ordered list or ol. Ordered list uses <ol> tag. To create an ordered list with roman number indexing we will use attribute type. The type attribute of the <ol> tag defines the numbering type of the list items. The default value of the type attribute in the ordered list is number. So for example, if we want the list with alphabets we simply give value “a” to type attribute. Similarly for creating a list with roman number indexing we have to provide the first roman number value to the type attribute. "
},
{
"code": null,
"e": 898,
"s": 890,
"text": "Syntax:"
},
{
"code": null,
"e": 912,
"s": 898,
"text": "<ol type=\"I\">"
},
{
"code": null,
"e": 963,
"s": 912,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1108,
"s": 965,
"text": "Example 1: In this example, we will create a list with uppercase roman number indexing. For that, we will provide attribute type value to “I”."
},
{
"code": null,
"e": 1113,
"s": 1108,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h2 { color: green; } </style></head> <body> <h2>Ordered List with Roman Numbers</h2> <ol type=\"I\"> <li>HTML</li> <li>CSS</li> <li>JAVA</li> <li>SASS</li> </ol></body> </html>",
"e": 1396,
"s": 1113,
"text": null
},
{
"code": null,
"e": 1404,
"s": 1396,
"text": "Output:"
},
{
"code": null,
"e": 1408,
"s": 1404,
"text": "GFG"
},
{
"code": null,
"e": 1592,
"s": 1408,
"text": "Example 2: Now we will create a list with lowercase roman number indexing. The entire code will be the same as before we will just change the type attribute value from “I” to “i” now."
},
{
"code": null,
"e": 1597,
"s": 1592,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h2 { color: green; } </style></head> <body> <h2> Ordered List with LowerCase Roman Numbers </h2> <ol type=\"i\"> <li>HTML</li> <li>CSS</li> <li>JAVA</li> <li>SASS</li> </ol></body> </html>",
"e": 1916,
"s": 1597,
"text": null
},
{
"code": null,
"e": 1924,
"s": 1916,
"text": "Output:"
},
{
"code": null,
"e": 1928,
"s": 1924,
"text": "GFG"
},
{
"code": null,
"e": 1944,
"s": 1928,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1959,
"s": 1944,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1969,
"s": 1959,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1976,
"s": 1969,
"text": "Picked"
},
{
"code": null,
"e": 1981,
"s": 1976,
"text": "HTML"
},
{
"code": null,
"e": 1998,
"s": 1981,
"text": "Web Technologies"
},
{
"code": null,
"e": 2003,
"s": 1998,
"text": "HTML"
}
]
|
How to access structure elements using Pointers in C# | 26 Feb, 2019
Unlike C/C++, Structures in C# can have members that are methods, fields, indexers, operator methods, properties or events. The members can have access specifiers as public, private, and internal.Pointers are variables that store the addresses of the same type of variable i.e. an int pointer can store an address of an integer, a char pointer can store an address of a char and similarly for all other data types, fundamental or user-defined.
You can access a structure member using pointers, of type structure, in the following ways;
1) Using the arrow operator: If the members of the structure are public then you can directly access them using the arrow operator ( -> ). If they are private then you can define methods for accessing the values and use pointers to access the methods. The arrow operator can be used to access structure variables as well as methods.
Syntax:
PointerName->memberName;
Example:
// C# Program to show the use of // pointers to access struct membersusing System; namespace GFG { // Defining a struct Studentstruct Student{ // With members // roll number and marks public int rno; public double marks; // Constructor to initialize values public Student(int r, double m) { rno = r; marks = m; }}; // end of struct Student class Program { // Main Method static void Main(string[] args) { // unsafe so as to use pointers unsafe { // Declaring two Student Variables Student S1 = new Student(1, 95.0); Student S2 = new Student(2, 79.5); // Declaring two Student pointers // and initializing them with addresses // of S1 and S2 Student* S1_ptr = &S1; Student* S2_ptr = &S2; // Displaying details of Student using pointers // Using the arrow ( -> ) operator Console.WriteLine("Details of Student 1"); Console.WriteLine("Roll Number: {0} Marks: {1}", S1_ptr -> rno, S1_ptr -> marks); Console.WriteLine("Details of Student 2"); Console.WriteLine("Roll Number: {0} Marks: {1}", S2_ptr -> rno, S2_ptr -> marks); } // end unsafe } // end main } // end class }
Output:
2) Using Dereferencing operator: You can also access structure elements using the dereferencing operator on the pointer, which is using an asterisk to dereference the pointer and then using the dot operator to specify the structure element.
Syntax:
(*PointerName).MemberName;
Example:
// C# Program to illustrate the use // of dereferencing operatorusing System; namespace GFG { // Defining struct Employeestruct Employee{ // Elements Eid and Salary // With properties get and set public int Eid { get; set; } public double Salary{ get; set;}}; // Employee ends class Program { // Main Method static void Main(string[] args) { // unsafe so as to use pointers unsafe { // Declaring a variable of type Employee Employee E1; // Declaring pointer of type Employee // initialized to point to E1 Employee* ptr = &E1; // Accessing struct elements using // dereferencing operator // calls the set accessor (*ptr).Eid = 1101; (*ptr).Salary = 1000.00; Console.WriteLine("Details of Employee"); // calls the get accessor Console.WriteLine("Employee Id: {0}\nSalary: {1}", (*ptr).Eid, (*ptr).Salary); } // end unsafe } // end Main } // end class }
Output:
Note: To compile unsafe code on Visual Studio (2012), Go to Project –> ProjectName Properties –> Build –> Check the “Allow unsafe code” box.
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 498,
"s": 54,
"text": "Unlike C/C++, Structures in C# can have members that are methods, fields, indexers, operator methods, properties or events. The members can have access specifiers as public, private, and internal.Pointers are variables that store the addresses of the same type of variable i.e. an int pointer can store an address of an integer, a char pointer can store an address of a char and similarly for all other data types, fundamental or user-defined."
},
{
"code": null,
"e": 590,
"s": 498,
"text": "You can access a structure member using pointers, of type structure, in the following ways;"
},
{
"code": null,
"e": 923,
"s": 590,
"text": "1) Using the arrow operator: If the members of the structure are public then you can directly access them using the arrow operator ( -> ). If they are private then you can define methods for accessing the values and use pointers to access the methods. The arrow operator can be used to access structure variables as well as methods."
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Syntax:"
},
{
"code": null,
"e": 956,
"s": 931,
"text": "PointerName->memberName;"
},
{
"code": null,
"e": 965,
"s": 956,
"text": "Example:"
},
{
"code": "// C# Program to show the use of // pointers to access struct membersusing System; namespace GFG { // Defining a struct Studentstruct Student{ // With members // roll number and marks public int rno; public double marks; // Constructor to initialize values public Student(int r, double m) { rno = r; marks = m; }}; // end of struct Student class Program { // Main Method static void Main(string[] args) { // unsafe so as to use pointers unsafe { // Declaring two Student Variables Student S1 = new Student(1, 95.0); Student S2 = new Student(2, 79.5); // Declaring two Student pointers // and initializing them with addresses // of S1 and S2 Student* S1_ptr = &S1; Student* S2_ptr = &S2; // Displaying details of Student using pointers // Using the arrow ( -> ) operator Console.WriteLine(\"Details of Student 1\"); Console.WriteLine(\"Roll Number: {0} Marks: {1}\", S1_ptr -> rno, S1_ptr -> marks); Console.WriteLine(\"Details of Student 2\"); Console.WriteLine(\"Roll Number: {0} Marks: {1}\", S2_ptr -> rno, S2_ptr -> marks); } // end unsafe } // end main } // end class }",
"e": 2341,
"s": 965,
"text": null
},
{
"code": null,
"e": 2349,
"s": 2341,
"text": "Output:"
},
{
"code": null,
"e": 2590,
"s": 2349,
"text": "2) Using Dereferencing operator: You can also access structure elements using the dereferencing operator on the pointer, which is using an asterisk to dereference the pointer and then using the dot operator to specify the structure element."
},
{
"code": null,
"e": 2598,
"s": 2590,
"text": "Syntax:"
},
{
"code": null,
"e": 2625,
"s": 2598,
"text": "(*PointerName).MemberName;"
},
{
"code": null,
"e": 2634,
"s": 2625,
"text": "Example:"
},
{
"code": "// C# Program to illustrate the use // of dereferencing operatorusing System; namespace GFG { // Defining struct Employeestruct Employee{ // Elements Eid and Salary // With properties get and set public int Eid { get; set; } public double Salary{ get; set;}}; // Employee ends class Program { // Main Method static void Main(string[] args) { // unsafe so as to use pointers unsafe { // Declaring a variable of type Employee Employee E1; // Declaring pointer of type Employee // initialized to point to E1 Employee* ptr = &E1; // Accessing struct elements using // dereferencing operator // calls the set accessor (*ptr).Eid = 1101; (*ptr).Salary = 1000.00; Console.WriteLine(\"Details of Employee\"); // calls the get accessor Console.WriteLine(\"Employee Id: {0}\\nSalary: {1}\", (*ptr).Eid, (*ptr).Salary); } // end unsafe } // end Main } // end class }",
"e": 3763,
"s": 2634,
"text": null
},
{
"code": null,
"e": 3771,
"s": 3763,
"text": "Output:"
},
{
"code": null,
"e": 3912,
"s": 3771,
"text": "Note: To compile unsafe code on Visual Studio (2012), Go to Project –> ProjectName Properties –> Build –> Check the “Allow unsafe code” box."
},
{
"code": null,
"e": 3915,
"s": 3912,
"text": "C#"
}
]
|
JSON web token | JWT | 21 Dec, 2021
A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange.The token is mainly composed of header, payload, signature. These three parts are separated by dots(.). JWT defines the structure of information we are sending from one party to the another, and it comes in two forms – Serialized, Deserialized. The Serialized approach is mainly used to transfer the data through the network with each request and response. While the deserialized approach is used to read and write data to the web token.
Deserialized
JWT in the deserialized form contains only the header and the payload.Both of them are plain JSON objects.
Header
A header in a JWT is mostly used to describe the cryptographic operations applied to the JWT like signing/decryption technique used on it. It can also contain the data about the media/content type of the information we are sending.This information is present as a JSON object then this JSON object is encoded to BASE64URL. The cryptographic operations in the header define whether the JWT is signed/unsigned or encrypted and are so then what algorithm techniques to use. A simple header of a JWT looks like the code below:
{
"typ":"JWT",
"alg":"HS256"
}
The ‘alg’ and ‘typ’ are object key’s having different values and different functions like the ‘typ’ gives us the type of the header this information packet is, whereas the ‘alg’ tells us about the encryption algorithm used.Note: HS256 and RS256 are the two main algorithms we make use of in the header section of a JWT.Some JWT’s can also be created without a signature or encryption. Such a token is referred to as unsecured and its header should have the value of the alg object key assigned to as ‘none’.
{
"alg":"none"
}
Payload
The payload is the part of the JWT where all the user data is actually added. This data is also referred to as the ‘claims’ of the JWT.This information is readable by anyone so it is always advised to not put any confidential information in here. This part generally contains user information. This information is present as a JSON object then this JSON object is encoded to BASE64URL. We can put as many claims as we want inside a payload, though unlike header, no claims are mandatory in a payload. The JWT with the payload will look something like this:
{
"userId":"b07f85be-45da",
"iss": "https://provider.domain.com/",
"sub": "auth/some-hash-here",
"exp": 153452683
}
The above JWT contains userId,iss,sub,and exp. All these play a different role as userId is the ID of the user we are storing, ‘iss’ tells us about the issuer, ‘sub’ stands for subject, and ‘exp’ stands for expiration date.
Serialized
JWT in the serialized form represents a string of the following format:
[header].[payload].[signature]
all these three components make up the serialized JWT. We already know what header and payload are and what they are used for.Let’s talk about signature.
Signature
This is the third part of JWT and used to verify the authenticity of token. BASE64URL encoded header and payload are joined together with dot(.) and it is then hashed using the hashing algorithm defined in a header with a secret key. This signature is then appended to header and payload using dot(.) which forms our actual token header.payload.signature
Syntax :
HASHINGALGO( base64UrlEncode(header) + “.” + base64UrlEncode(payload),secret)
So all these above components together are what makes up a JWT. Now let’s see how our actual token will look like:
JWT Example :
header:
{
"alg" : "HS256",
"typ" : "JWT"
}
Payload:
{
"id" : 123456789,
"name" : "Joseph"
}
Secret: GeeksForGeeks
JSON Web Token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2Nzg5LCJuYW1lIjoiSm9zZXBoIn0.OpOSSw7e485LOP5PrzScxHb7SR6sAOMRckfFwi4rp7o
iamamansharma98
JSON
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 701,
"s": 54,
"text": "A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange.The token is mainly composed of header, payload, signature. These three parts are separated by dots(.). JWT defines the structure of information we are sending from one party to the another, and it comes in two forms – Serialized, Deserialized. The Serialized approach is mainly used to transfer the data through the network with each request and response. While the deserialized approach is used to read and write data to the web token."
},
{
"code": null,
"e": 714,
"s": 701,
"text": "Deserialized"
},
{
"code": null,
"e": 821,
"s": 714,
"text": "JWT in the deserialized form contains only the header and the payload.Both of them are plain JSON objects."
},
{
"code": null,
"e": 828,
"s": 821,
"text": "Header"
},
{
"code": null,
"e": 1351,
"s": 828,
"text": "A header in a JWT is mostly used to describe the cryptographic operations applied to the JWT like signing/decryption technique used on it. It can also contain the data about the media/content type of the information we are sending.This information is present as a JSON object then this JSON object is encoded to BASE64URL. The cryptographic operations in the header define whether the JWT is signed/unsigned or encrypted and are so then what algorithm techniques to use. A simple header of a JWT looks like the code below:"
},
{
"code": null,
"e": 1393,
"s": 1351,
"text": " {\n \"typ\":\"JWT\",\n \"alg\":\"HS256\"\n }\n"
},
{
"code": null,
"e": 1901,
"s": 1393,
"text": "The ‘alg’ and ‘typ’ are object key’s having different values and different functions like the ‘typ’ gives us the type of the header this information packet is, whereas the ‘alg’ tells us about the encryption algorithm used.Note: HS256 and RS256 are the two main algorithms we make use of in the header section of a JWT.Some JWT’s can also be created without a signature or encryption. Such a token is referred to as unsecured and its header should have the value of the alg object key assigned to as ‘none’."
},
{
"code": null,
"e": 1925,
"s": 1901,
"text": " {\n \"alg\":\"none\"\n }\n"
},
{
"code": null,
"e": 1933,
"s": 1925,
"text": "Payload"
},
{
"code": null,
"e": 2490,
"s": 1933,
"text": "The payload is the part of the JWT where all the user data is actually added. This data is also referred to as the ‘claims’ of the JWT.This information is readable by anyone so it is always advised to not put any confidential information in here. This part generally contains user information. This information is present as a JSON object then this JSON object is encoded to BASE64URL. We can put as many claims as we want inside a payload, though unlike header, no claims are mandatory in a payload. The JWT with the payload will look something like this:"
},
{
"code": null,
"e": 2629,
"s": 2490,
"text": " {\n \"userId\":\"b07f85be-45da\",\n \"iss\": \"https://provider.domain.com/\",\n \"sub\": \"auth/some-hash-here\",\n \"exp\": 153452683\n }\n"
},
{
"code": null,
"e": 2853,
"s": 2629,
"text": "The above JWT contains userId,iss,sub,and exp. All these play a different role as userId is the ID of the user we are storing, ‘iss’ tells us about the issuer, ‘sub’ stands for subject, and ‘exp’ stands for expiration date."
},
{
"code": null,
"e": 2864,
"s": 2853,
"text": "Serialized"
},
{
"code": null,
"e": 2936,
"s": 2864,
"text": "JWT in the serialized form represents a string of the following format:"
},
{
"code": null,
"e": 2968,
"s": 2936,
"text": "[header].[payload].[signature]\n"
},
{
"code": null,
"e": 3122,
"s": 2968,
"text": "all these three components make up the serialized JWT. We already know what header and payload are and what they are used for.Let’s talk about signature."
},
{
"code": null,
"e": 3132,
"s": 3122,
"text": "Signature"
},
{
"code": null,
"e": 3487,
"s": 3132,
"text": "This is the third part of JWT and used to verify the authenticity of token. BASE64URL encoded header and payload are joined together with dot(.) and it is then hashed using the hashing algorithm defined in a header with a secret key. This signature is then appended to header and payload using dot(.) which forms our actual token header.payload.signature"
},
{
"code": null,
"e": 3496,
"s": 3487,
"text": "Syntax :"
},
{
"code": null,
"e": 3574,
"s": 3496,
"text": "HASHINGALGO( base64UrlEncode(header) + “.” + base64UrlEncode(payload),secret)"
},
{
"code": null,
"e": 3689,
"s": 3574,
"text": "So all these above components together are what makes up a JWT. Now let’s see how our actual token will look like:"
},
{
"code": null,
"e": 3703,
"s": 3689,
"text": "JWT Example :"
},
{
"code": null,
"e": 3832,
"s": 3703,
"text": "header:\n\n{\n \"alg\" : \"HS256\",\n\n \"typ\" : \"JWT\"\n}\n\nPayload:\n\n{\n \"id\" : 123456789,\n\n \"name\" : \"Joseph\"\n}\n\nSecret: GeeksForGeeks\n"
},
{
"code": null,
"e": 3847,
"s": 3832,
"text": "JSON Web Token"
},
{
"code": null,
"e": 3972,
"s": 3847,
"text": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2Nzg5LCJuYW1lIjoiSm9zZXBoIn0.OpOSSw7e485LOP5PrzScxHb7SR6sAOMRckfFwi4rp7o"
},
{
"code": null,
"e": 3988,
"s": 3972,
"text": "iamamansharma98"
},
{
"code": null,
"e": 3993,
"s": 3988,
"text": "JSON"
},
{
"code": null,
"e": 4004,
"s": 3993,
"text": "JavaScript"
},
{
"code": null,
"e": 4021,
"s": 4004,
"text": "Web Technologies"
}
]
|
How to set the Background color of the Button in C#? | 26 Jun, 2019
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Windows form, you are allowed to set the background color of the button with the help of BackColor property. This property is provided by Button class and helps programmers to create more good looking buttons in their forms. You can use this property in two different methods:
1. Design-Time: It is the easiest method to set the background color of the button. Using the following steps you will set the background color of your button:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Button control to set the BackColor property of the Button.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BackColor property of the Button programmatically with the help of given syntax:
public override System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the button. Following steps are used to set the BackColor property of the Button:
Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class
Button MyButton = new Button();
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating Button, set the BackColor property of the Button provided by the Button class.// Set the BackColor property of the button
Mybutton.BackColor = Color.LightBlue;
// Set the BackColor property of the button
Mybutton.BackColor = Color.LightBlue;
Step 3: And last add this button control to from using Add() method.// Add this Button to form
this.Controls.Add(Mybutton);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:
// Add this Button to form
this.Controls.Add(Mybutton);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 447,
"s": 28,
"text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Windows form, you are allowed to set the background color of the button with the help of BackColor property. This property is provided by Button class and helps programmers to create more good looking buttons in their forms. You can use this property in two different methods:"
},
{
"code": null,
"e": 607,
"s": 447,
"text": "1. Design-Time: It is the easiest method to set the background color of the button. Using the following steps you will set the background color of your button:"
},
{
"code": null,
"e": 723,
"s": 607,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 900,
"s": 723,
"text": "Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1032,
"s": 900,
"text": "Step 3: After drag and drop you will go to the properties of the Button control to set the BackColor property of the Button.Output:"
},
{
"code": null,
"e": 1040,
"s": 1032,
"text": "Output:"
},
{
"code": null,
"e": 1217,
"s": 1040,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BackColor property of the Button programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1278,
"s": 1217,
"text": "public override System.Drawing.Color BackColor { get; set; }"
},
{
"code": null,
"e": 1406,
"s": 1278,
"text": "Here, Color indicates the background color of the button. Following steps are used to set the BackColor property of the Button:"
},
{
"code": null,
"e": 1564,
"s": 1406,
"text": "Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 1635,
"s": 1564,
"text": "// Creating Button using Button class\nButton MyButton = new Button();\n"
},
{
"code": null,
"e": 1819,
"s": 1635,
"text": "Step 2: After creating Button, set the BackColor property of the Button provided by the Button class.// Set the BackColor property of the button\nMybutton.BackColor = Color.LightBlue;\n"
},
{
"code": null,
"e": 1902,
"s": 1819,
"text": "// Set the BackColor property of the button\nMybutton.BackColor = Color.LightBlue;\n"
},
{
"code": null,
"e": 3384,
"s": 1902,
"text": "Step 3: And last add this button control to from using Add() method.// Add this Button to form\nthis.Controls.Add(Mybutton);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:"
},
{
"code": null,
"e": 3441,
"s": 3384,
"text": "// Add this Button to form\nthis.Controls.Add(Mybutton);\n"
},
{
"code": null,
"e": 3450,
"s": 3441,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; // Adding this button to form this.Controls.Add(Mybutton1); }}}",
"e": 4793,
"s": 3450,
"text": null
},
{
"code": null,
"e": 4801,
"s": 4793,
"text": "Output:"
},
{
"code": null,
"e": 4804,
"s": 4801,
"text": "C#"
}
]
|
Measures of Distance in Data Mining | 03 Feb, 2020
Clustering consists of grouping certain objects that are similar to each other, it can be used to decide if two items are similar or dissimilar in their properties.
In a Data Mining sense, the similarity measure is a distance with dimensions describing object features. That means if the distance among two data points is small then there is a high degree of similarity among the objects and vice versa. The similarity is subjective and depends heavily on the context and application. For example, similarity among vegetables can be determined from their taste, size, colour etc.
Most clustering approaches use distance measures to assess the similarities or differences between a pair of objects, the most popular distance measures used are:
1. Euclidean Distance:Euclidean distance is considered the traditional metric for problems with geometry. It can be simply explained as the ordinary distance between two points. It is one of the most used algorithms in the cluster analysis. One of the algorithms that use this formula would be K-mean. Mathematically it computes the root of squared differences between the coordinates between two objects.
2. Manhattan Distance:This determines the absolute difference among the pair of the coordinates.
Suppose we have two points P and Q to determine the distance between these points we simply have to calculate the perpendicular distance of the points from X-Axis and Y-Axis.In a plane with P at coordinate (x1, y1) and Q at (x2, y2).
Manhattan distance between P and Q = |x1 – x2| + |y1 – y2|
Here the total distance of the Red line gives the Manhattan distance between both the points.
3. Jaccard Index:The Jaccard distance measures the similarity of the two data set items as the intersection of those items divided by the union of the data items.
4. Minkowski distance:It is the generalized form of the Euclidean and Manhattan Distance Measure. In an N-dimensional space, a point is represented as,
(x1, x2, ..., xN)
Consider two points P1 and P2:
P1: (X1, X2, ..., XN)
P2: (Y1, Y2, ..., YN)
Then, the Minkowski distance between P1 and P2 is given as:
When p = 2, Minkowski distance is same as the Euclidean distance.
When p = 1, Minkowski distance is same as the Manhattan distance.
5. Cosine Index:Cosine distance measure for clustering determines the cosine of the angle between two vectors given by the following formula.
Here (theta) gives the angle between two vectors and A, B are n-dimensional vectors.
data mining
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL | Views
SQL Interview Questions
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
Types of Functional dependencies in DBMS
Difference between Primary Key and Foreign Key
Difference between SQL and NoSQL | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2020"
},
{
"code": null,
"e": 217,
"s": 52,
"text": "Clustering consists of grouping certain objects that are similar to each other, it can be used to decide if two items are similar or dissimilar in their properties."
},
{
"code": null,
"e": 632,
"s": 217,
"text": "In a Data Mining sense, the similarity measure is a distance with dimensions describing object features. That means if the distance among two data points is small then there is a high degree of similarity among the objects and vice versa. The similarity is subjective and depends heavily on the context and application. For example, similarity among vegetables can be determined from their taste, size, colour etc."
},
{
"code": null,
"e": 795,
"s": 632,
"text": "Most clustering approaches use distance measures to assess the similarities or differences between a pair of objects, the most popular distance measures used are:"
},
{
"code": null,
"e": 1201,
"s": 795,
"text": "1. Euclidean Distance:Euclidean distance is considered the traditional metric for problems with geometry. It can be simply explained as the ordinary distance between two points. It is one of the most used algorithms in the cluster analysis. One of the algorithms that use this formula would be K-mean. Mathematically it computes the root of squared differences between the coordinates between two objects."
},
{
"code": null,
"e": 1298,
"s": 1201,
"text": "2. Manhattan Distance:This determines the absolute difference among the pair of the coordinates."
},
{
"code": null,
"e": 1532,
"s": 1298,
"text": "Suppose we have two points P and Q to determine the distance between these points we simply have to calculate the perpendicular distance of the points from X-Axis and Y-Axis.In a plane with P at coordinate (x1, y1) and Q at (x2, y2)."
},
{
"code": null,
"e": 1591,
"s": 1532,
"text": "Manhattan distance between P and Q = |x1 – x2| + |y1 – y2|"
},
{
"code": null,
"e": 1685,
"s": 1591,
"text": "Here the total distance of the Red line gives the Manhattan distance between both the points."
},
{
"code": null,
"e": 1848,
"s": 1685,
"text": "3. Jaccard Index:The Jaccard distance measures the similarity of the two data set items as the intersection of those items divided by the union of the data items."
},
{
"code": null,
"e": 2000,
"s": 1848,
"text": "4. Minkowski distance:It is the generalized form of the Euclidean and Manhattan Distance Measure. In an N-dimensional space, a point is represented as,"
},
{
"code": null,
"e": 2019,
"s": 2000,
"text": "(x1, x2, ..., xN) "
},
{
"code": null,
"e": 2050,
"s": 2019,
"text": "Consider two points P1 and P2:"
},
{
"code": null,
"e": 2095,
"s": 2050,
"text": "P1: (X1, X2, ..., XN)\nP2: (Y1, Y2, ..., YN) "
},
{
"code": null,
"e": 2155,
"s": 2095,
"text": "Then, the Minkowski distance between P1 and P2 is given as:"
},
{
"code": null,
"e": 2221,
"s": 2155,
"text": "When p = 2, Minkowski distance is same as the Euclidean distance."
},
{
"code": null,
"e": 2287,
"s": 2221,
"text": "When p = 1, Minkowski distance is same as the Manhattan distance."
},
{
"code": null,
"e": 2429,
"s": 2287,
"text": "5. Cosine Index:Cosine distance measure for clustering determines the cosine of the angle between two vectors given by the following formula."
},
{
"code": null,
"e": 2514,
"s": 2429,
"text": "Here (theta) gives the angle between two vectors and A, B are n-dimensional vectors."
},
{
"code": null,
"e": 2526,
"s": 2514,
"text": "data mining"
},
{
"code": null,
"e": 2531,
"s": 2526,
"text": "DBMS"
},
{
"code": null,
"e": 2536,
"s": 2531,
"text": "DBMS"
},
{
"code": null,
"e": 2634,
"s": 2536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2645,
"s": 2634,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2698,
"s": 2645,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2721,
"s": 2698,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 2733,
"s": 2721,
"text": "SQL | Views"
},
{
"code": null,
"e": 2757,
"s": 2733,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2796,
"s": 2757,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 2841,
"s": 2796,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2882,
"s": 2841,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 2929,
"s": 2882,
"text": "Difference between Primary Key and Foreign Key"
}
]
|
Kali Linux – Web Penetration Testing Tools | 17 Dec, 2021
By 2016, there were around 3424971237+ internet users over the world. Being a hub of many users, there comes a responsibility of taking care of the security of these many users. Most of the Internet is the collection of websites or web applications. So in order to prevent these web applications, there is a need of testing them again payloads and malware and for that purpose, we have a lot of tools in Kali Linux.
Kali Linux comes packed with 300+ tools out of which many are used for Web Penetration Testing. Though there are many tools in Kali Linux for Web Penetration Testing here is the list of most used tools.
Burp Suite is one of the most popular web application security testing software. It is used as a proxy, so all the requests from the browser with the proxy pass through it. And as the request passes through the burp suite, it allows us to make changes to those requests as per our need which is good for testing vulnerabilities like XSS or SQLi or even any vulnerability related to the web. Kali Linux comes with burp suite community edition which is free but there is a paid edition of this tool known as burp suite professional which has a lot many functions as compared to burp suite community edition.
To use burp suite:
Read this to learn how to setup burp suite.
Open terminal and type “burpsuite” there.
Go to proxy tab and turn the interceptor switch to on.
Now visit any URL and it could be seen that the request is captured.
Nikto is an Open Source software written in Perl language that is used to scan a web-server for the vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 servers and can detect problems with specific version details of over 200 servers. It comes packed with many features, a few of them are listed below.
Full support for SSL
Looks for subdomains
Supports full HTTP Proxy
Outdated component report
Username guessing
To use nikto, download nikto and enter the following command.
perl nikto.pl -H
Maltego is a platform developed to convey and put forward a clear picture of the environment that an organization owns and operates. Maltego offers a unique perspective to both network and resource-based entities which is the aggregation of information delivered all over the internet – whether it’s the current configuration of a router poised on the edge of our network or any other information, Maltego can locate, aggregate and visualize this information. It offers the user with unprecedented information which is leverage and power.
Maltego’s Uses:
It is used to exhibit the complexity and severity of single points of failure as well as trust relationships that exist currently within the scope of the infrastructure.
It is used in the collection of information on all security-related work. It will save time and will allow us to work more accurately and in a smarter way.
It aids us in thinking process by visually demonstrating interconnected links between searched items.
It provides a much more powerful search, giving smarter results.
It helps to discover “hidden” information.
To use Maltego, Go to applications menu and then select “maltego” tool to execute it.
SQLMap is an open-source tool that is used to automate the process of manual SQL injection over a parameter on a website. It detects and exploits the SQL injection parameters itself all we have to do is to provide it with an appropriate request or URL. It supports 34 databases including MySQL, Oracle, PostgreSQL, etc.
To use sqlmap tool:
sqlmap comes pre-installed in Kali Linux
Just type sqlmap in the terminal to use the tool.
Whatweb is an acronym of “what is that website“.It is used to get the technologies which a website is using, these technologies might me content management system(CMS), Javascript Libraries, etc. It is used for many purposes, a few of them are listed below.
To get the Content Management System is used by a web application
To get the Web Server details being used by the web application
To get the embedded devices attached to the web application
It consists of 1700+ plugins and every plugin is used to recognize something different.
To run whatweb, execute the following command and replace google.com with the domain name of your choice.
whatweb google.com
whois is a database record of all the registered domain over the internet. It is used for many purposes, a few of them are listed below.
It is used by Network Administrators in order to identify and fix DNS or domain-related issues.
It is used to check the availability of domain names.
It is used to identify trademark infringement.
It could even be used to track down the registrants of the Fraud domain.
To use whois lookup, enter the following command in the terminal.
whois geeksforgeeks.org
Replace geeksforgeeks.org with the name of the website you want to lookup.
abhishek0719kadiyan
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 444,
"s": 28,
"text": "By 2016, there were around 3424971237+ internet users over the world. Being a hub of many users, there comes a responsibility of taking care of the security of these many users. Most of the Internet is the collection of websites or web applications. So in order to prevent these web applications, there is a need of testing them again payloads and malware and for that purpose, we have a lot of tools in Kali Linux."
},
{
"code": null,
"e": 647,
"s": 444,
"text": "Kali Linux comes packed with 300+ tools out of which many are used for Web Penetration Testing. Though there are many tools in Kali Linux for Web Penetration Testing here is the list of most used tools."
},
{
"code": null,
"e": 1253,
"s": 647,
"text": "Burp Suite is one of the most popular web application security testing software. It is used as a proxy, so all the requests from the browser with the proxy pass through it. And as the request passes through the burp suite, it allows us to make changes to those requests as per our need which is good for testing vulnerabilities like XSS or SQLi or even any vulnerability related to the web. Kali Linux comes with burp suite community edition which is free but there is a paid edition of this tool known as burp suite professional which has a lot many functions as compared to burp suite community edition."
},
{
"code": null,
"e": 1272,
"s": 1253,
"text": "To use burp suite:"
},
{
"code": null,
"e": 1316,
"s": 1272,
"text": "Read this to learn how to setup burp suite."
},
{
"code": null,
"e": 1358,
"s": 1316,
"text": "Open terminal and type “burpsuite” there."
},
{
"code": null,
"e": 1413,
"s": 1358,
"text": "Go to proxy tab and turn the interceptor switch to on."
},
{
"code": null,
"e": 1482,
"s": 1413,
"text": "Now visit any URL and it could be seen that the request is captured."
},
{
"code": null,
"e": 1855,
"s": 1482,
"text": "Nikto is an Open Source software written in Perl language that is used to scan a web-server for the vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 servers and can detect problems with specific version details of over 200 servers. It comes packed with many features, a few of them are listed below."
},
{
"code": null,
"e": 1876,
"s": 1855,
"text": "Full support for SSL"
},
{
"code": null,
"e": 1897,
"s": 1876,
"text": "Looks for subdomains"
},
{
"code": null,
"e": 1922,
"s": 1897,
"text": "Supports full HTTP Proxy"
},
{
"code": null,
"e": 1948,
"s": 1922,
"text": "Outdated component report"
},
{
"code": null,
"e": 1966,
"s": 1948,
"text": "Username guessing"
},
{
"code": null,
"e": 2028,
"s": 1966,
"text": "To use nikto, download nikto and enter the following command."
},
{
"code": null,
"e": 2045,
"s": 2028,
"text": "perl nikto.pl -H"
},
{
"code": null,
"e": 2584,
"s": 2045,
"text": "Maltego is a platform developed to convey and put forward a clear picture of the environment that an organization owns and operates. Maltego offers a unique perspective to both network and resource-based entities which is the aggregation of information delivered all over the internet – whether it’s the current configuration of a router poised on the edge of our network or any other information, Maltego can locate, aggregate and visualize this information. It offers the user with unprecedented information which is leverage and power."
},
{
"code": null,
"e": 2600,
"s": 2584,
"text": "Maltego’s Uses:"
},
{
"code": null,
"e": 2770,
"s": 2600,
"text": "It is used to exhibit the complexity and severity of single points of failure as well as trust relationships that exist currently within the scope of the infrastructure."
},
{
"code": null,
"e": 2926,
"s": 2770,
"text": "It is used in the collection of information on all security-related work. It will save time and will allow us to work more accurately and in a smarter way."
},
{
"code": null,
"e": 3028,
"s": 2926,
"text": "It aids us in thinking process by visually demonstrating interconnected links between searched items."
},
{
"code": null,
"e": 3093,
"s": 3028,
"text": "It provides a much more powerful search, giving smarter results."
},
{
"code": null,
"e": 3136,
"s": 3093,
"text": "It helps to discover “hidden” information."
},
{
"code": null,
"e": 3222,
"s": 3136,
"text": "To use Maltego, Go to applications menu and then select “maltego” tool to execute it."
},
{
"code": null,
"e": 3542,
"s": 3222,
"text": "SQLMap is an open-source tool that is used to automate the process of manual SQL injection over a parameter on a website. It detects and exploits the SQL injection parameters itself all we have to do is to provide it with an appropriate request or URL. It supports 34 databases including MySQL, Oracle, PostgreSQL, etc."
},
{
"code": null,
"e": 3562,
"s": 3542,
"text": "To use sqlmap tool:"
},
{
"code": null,
"e": 3603,
"s": 3562,
"text": "sqlmap comes pre-installed in Kali Linux"
},
{
"code": null,
"e": 3653,
"s": 3603,
"text": "Just type sqlmap in the terminal to use the tool."
},
{
"code": null,
"e": 3911,
"s": 3653,
"text": "Whatweb is an acronym of “what is that website“.It is used to get the technologies which a website is using, these technologies might me content management system(CMS), Javascript Libraries, etc. It is used for many purposes, a few of them are listed below."
},
{
"code": null,
"e": 3977,
"s": 3911,
"text": "To get the Content Management System is used by a web application"
},
{
"code": null,
"e": 4041,
"s": 3977,
"text": "To get the Web Server details being used by the web application"
},
{
"code": null,
"e": 4101,
"s": 4041,
"text": "To get the embedded devices attached to the web application"
},
{
"code": null,
"e": 4189,
"s": 4101,
"text": "It consists of 1700+ plugins and every plugin is used to recognize something different."
},
{
"code": null,
"e": 4295,
"s": 4189,
"text": "To run whatweb, execute the following command and replace google.com with the domain name of your choice."
},
{
"code": null,
"e": 4314,
"s": 4295,
"text": "whatweb google.com"
},
{
"code": null,
"e": 4451,
"s": 4314,
"text": "whois is a database record of all the registered domain over the internet. It is used for many purposes, a few of them are listed below."
},
{
"code": null,
"e": 4547,
"s": 4451,
"text": "It is used by Network Administrators in order to identify and fix DNS or domain-related issues."
},
{
"code": null,
"e": 4601,
"s": 4547,
"text": "It is used to check the availability of domain names."
},
{
"code": null,
"e": 4648,
"s": 4601,
"text": "It is used to identify trademark infringement."
},
{
"code": null,
"e": 4721,
"s": 4648,
"text": "It could even be used to track down the registrants of the Fraud domain."
},
{
"code": null,
"e": 4787,
"s": 4721,
"text": "To use whois lookup, enter the following command in the terminal."
},
{
"code": null,
"e": 4811,
"s": 4787,
"text": "whois geeksforgeeks.org"
},
{
"code": null,
"e": 4886,
"s": 4811,
"text": "Replace geeksforgeeks.org with the name of the website you want to lookup."
},
{
"code": null,
"e": 4906,
"s": 4886,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 4917,
"s": 4906,
"text": "Kali-Linux"
},
{
"code": null,
"e": 4928,
"s": 4917,
"text": "Linux-Unix"
}
]
|
How to access an object having spaces in the object’s key using JavaScript ? | 17 Sep, 2019
Given an object and the task is to access the object in which key contains spaces. There are few methods to solve this problem which are discussed below:
Approach 1:
Create an object having space separated keys.
Use square bracket notation instead of dot notation to access the property.
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Access a JavaScript object having spaces in the object's key. </title></head> <body id="body" align="center"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var JSObject = { 'Geeks': { Geeks1: 'Geeks1_val', Geeks2: 'Geeks2_val' }, 'Computer Science portal': { Geeks_1: 'A Computer Science portal for Geeks.', Geeks_2: 'Geeks_2_val' } } el_up.innerHTML = "Click on the button to access the "+ "key of object<br><br>"+ JSON.stringify(JSObject); function GFG_Fun() { el_down.innerHTML = JSObject['Computer Science portal'].Geeks_1; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Create an object having space separated keys.
Take the key in a variable and use that variable in place of key (But, Here also square bracket notation will work).
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Access a JavaScript object having spaces in the object's key. </title></head> <body id="body" align="center"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var JSObject = { 'Geeks': { Geeks1: 'Geeks1_val', Geeks2: 'Geeks2_val' }, 'Computer Science portal': { Geeks_1: 'A Computer Science portal for Geeks.', Geeks_2: 'Geeks_2_val' } } el_up.innerHTML = "Click on the button to access "+ "the key of object<br><br>" + JSON.stringify(JSObject); function GFG_Fun() { var someKey = 'Computer Science portal'; el_down.innerHTML = JSObject[someKey].Geeks_1; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
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
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 182,
"s": 28,
"text": "Given an object and the task is to access the object in which key contains spaces. There are few methods to solve this problem which are discussed below:"
},
{
"code": null,
"e": 194,
"s": 182,
"text": "Approach 1:"
},
{
"code": null,
"e": 240,
"s": 194,
"text": "Create an object having space separated keys."
},
{
"code": null,
"e": 316,
"s": 240,
"text": "Use square bracket notation instead of dot notation to access the property."
},
{
"code": null,
"e": 369,
"s": 316,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Access a JavaScript object having spaces in the object's key. </title></head> <body id=\"body\" align=\"center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var JSObject = { 'Geeks': { Geeks1: 'Geeks1_val', Geeks2: 'Geeks2_val' }, 'Computer Science portal': { Geeks_1: 'A Computer Science portal for Geeks.', Geeks_2: 'Geeks_2_val' } } el_up.innerHTML = \"Click on the button to access the \"+ \"key of object<br><br>\"+ JSON.stringify(JSObject); function GFG_Fun() { el_down.innerHTML = JSObject['Computer Science portal'].Geeks_1; } </script></body> </html>",
"e": 1542,
"s": 369,
"text": null
},
{
"code": null,
"e": 1550,
"s": 1542,
"text": "Output:"
},
{
"code": null,
"e": 1581,
"s": 1550,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1611,
"s": 1581,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1623,
"s": 1611,
"text": "Approach 2:"
},
{
"code": null,
"e": 1669,
"s": 1623,
"text": "Create an object having space separated keys."
},
{
"code": null,
"e": 1786,
"s": 1669,
"text": "Take the key in a variable and use that variable in place of key (But, Here also square bracket notation will work)."
},
{
"code": null,
"e": 1839,
"s": 1786,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Access a JavaScript object having spaces in the object's key. </title></head> <body id=\"body\" align=\"center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var JSObject = { 'Geeks': { Geeks1: 'Geeks1_val', Geeks2: 'Geeks2_val' }, 'Computer Science portal': { Geeks_1: 'A Computer Science portal for Geeks.', Geeks_2: 'Geeks_2_val' } } el_up.innerHTML = \"Click on the button to access \"+ \"the key of object<br><br>\" + JSON.stringify(JSObject); function GFG_Fun() { var someKey = 'Computer Science portal'; el_down.innerHTML = JSObject[someKey].Geeks_1; } </script></body> </html>",
"e": 3038,
"s": 1839,
"text": null
},
{
"code": null,
"e": 3046,
"s": 3038,
"text": "Output:"
},
{
"code": null,
"e": 3077,
"s": 3046,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3107,
"s": 3077,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3123,
"s": 3107,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3134,
"s": 3123,
"text": "JavaScript"
},
{
"code": null,
"e": 3151,
"s": 3134,
"text": "Web Technologies"
},
{
"code": null,
"e": 3178,
"s": 3151,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3276,
"s": 3178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3337,
"s": 3276,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3409,
"s": 3337,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3449,
"s": 3409,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3491,
"s": 3449,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3532,
"s": 3491,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3565,
"s": 3532,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3627,
"s": 3565,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3688,
"s": 3627,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3738,
"s": 3688,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
base64.urlsafe_b64encode(s) in Python | 26 Mar, 2020
With the help of base64.urlsafe_b64encode(s) method, we can encode the string using url and file system safe alphabets into the binary form.
Syntax : base64.urlsafe_b64encode(s)
Return : Return the encoded string.
Example #1 :In this example we can see that by using base64.urlsafe_b64encode(s) method, we are able to get the encoded string which can be in binary form by using this method.
# import base64from base64 import urlsafe_b64encode s = b'GeeksForGeeks'# Using base64.urlsafe_b64encode(s) methodgfg = urlsafe_b64encode(s) print(gfg)
Output :
b’R2Vla3NGb3JHZWVrcw==’
Example #2 :
# import base64from base64 import urlsafe_b64encode s = b'www.python.org / documentation'# Using base64.urlsafe_b64encode(s) methodgfg = urlsafe_b64encode(s) print(gfg)
Output :
b’d3d3LnB5dGhvbi5vcmcvZG9jdW1lbnRhdGlvbg==’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "With the help of base64.urlsafe_b64encode(s) method, we can encode the string using url and file system safe alphabets into the binary form."
},
{
"code": null,
"e": 206,
"s": 169,
"text": "Syntax : base64.urlsafe_b64encode(s)"
},
{
"code": null,
"e": 242,
"s": 206,
"text": "Return : Return the encoded string."
},
{
"code": null,
"e": 419,
"s": 242,
"text": "Example #1 :In this example we can see that by using base64.urlsafe_b64encode(s) method, we are able to get the encoded string which can be in binary form by using this method."
},
{
"code": "# import base64from base64 import urlsafe_b64encode s = b'GeeksForGeeks'# Using base64.urlsafe_b64encode(s) methodgfg = urlsafe_b64encode(s) print(gfg)",
"e": 573,
"s": 419,
"text": null
},
{
"code": null,
"e": 582,
"s": 573,
"text": "Output :"
},
{
"code": null,
"e": 606,
"s": 582,
"text": "b’R2Vla3NGb3JHZWVrcw==’"
},
{
"code": null,
"e": 619,
"s": 606,
"text": "Example #2 :"
},
{
"code": "# import base64from base64 import urlsafe_b64encode s = b'www.python.org / documentation'# Using base64.urlsafe_b64encode(s) methodgfg = urlsafe_b64encode(s) print(gfg)",
"e": 790,
"s": 619,
"text": null
},
{
"code": null,
"e": 799,
"s": 790,
"text": "Output :"
},
{
"code": null,
"e": 843,
"s": 799,
"text": "b’d3d3LnB5dGhvbi5vcmcvZG9jdW1lbnRhdGlvbg==’"
},
{
"code": null,
"e": 864,
"s": 843,
"text": "Python base64-module"
},
{
"code": null,
"e": 871,
"s": 864,
"text": "Python"
}
]
|
Callback using Interfaces in Java | 30 May, 2022
Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not exist in Java because Java doesn’t have pointer concept. However, there are situations where one could speak of a callback object or a callback interface. Instead of passing the memory address of a function, interface is passed that refers to the location of a function.
Example
Let us take an example to understand where callbacks can be used. Suppose a programmer wants to design a tax calculator that calculates total tax of a state. Assume there are only two taxes, central and state tax. Central tax is common whereas the state tax varies from one state to another. The total tax is the sum of the two. Here separate method like stateTax() is implemented for every state and call this method from another method calculateTax() as:
static void calculateTax(address of stateTax() function)
{
ct = 1000.0
st = calculate state tax depending on the address
total tax = ct+st;
}
In the preceding code, the address of stateTax() is passed to calculateTax(). The calculateTax() method will use that address to call stateTax() method of a particular state and the state tax ‘st’ is calculated. Since the code of stateTax() method changes from one state to another state, it is better to declare it as an abstract method in an interface, as:
interface STax
{
double stateTax();
}
The following is the implementation of stateTax() for Punjab state:
class Punjab implements STax{
public double stateTax(){
return 3000.0;
}
}
The following is the implementation of stateTax() for HP state:
class HP implements STax
{
public double stateTax()
{
return 1000.0;
}
}
Now, the calculateTax() method can be designed as:
static void calculateTax(STax t)
{
// calculate central tax
double ct = 2000.0;
// calculate state tax
double st = t.stateTax();
double totaltax = st + ct;
// display total tax
System.out.println(“Total tax =”+totaltax);
}
Here, observe the parameter ‘STax t’ in the calculateTax() method. ‘t‘ is a reference of the ‘STax’ interface which is passed as a parameter to the method. Using this reference, the stateTax() method is called, as:
double st = t.stateTax();
Here, if ‘t’ refers to stateTax() method of class Punjab, then that method is called and its tax is calculated. Similarly, for class HP. In this way, by passing interface reference to calculateTax() method, it is possible to call stateTax() method of any state. This is called callback mechanism.By passing the interface reference that refers to a method, it is possible to call and use that method from another method.
Java
// Java program to demonstrate callback mechanism// using interface is Java // Create interfaceimport java.util.Scanner;interface STax { double stateTax();} // Implementation class of Punjab state taxclass Punjab implements STax { public double stateTax() { return 3000.0; }} // Implementation class of Himachal Pradesh state taxclass HP implements STax { public double stateTax() { return 1000.0; }} class TAX { public static void main(String[] args)throws ClassNotFoundException, IllegalAccessException, InstantiationException { Scanner sc = new Scanner(System.in); System.out.println("Enter the state name"); String state = sc.next(); // name of the state // The state name is then stored in an object c Class c = Class.forName(state); // Create the new object of the class whose name is in c // Stax interface reference is now referencing that new object STax ref = (STax)c.newInstance(); /*Call the method to calculate total tax and pass interface reference - this is callback . Here, ref may refer to stateTax() of Punjab or HP classes depending on the class for which the object is created in the previous step */ calculateTax(ref); } static void calculateTax(STax t) { // calculate central tax double ct = 2000.0; // calculate state tax double st = t.stateTax(); double totaltax = st + ct; // display total tax System.out.println("Total tax =" + totaltax); }}
Output:
Enter the state name
Punjab
Total tax = 5000.0
References: How to implement callback functions in Java? Core Java: An Integrated Approach
sushmakurellageeksforgeeks
surindertarika1234
simmytarika5
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 672,
"s": 52,
"text": "Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not exist in Java because Java doesn’t have pointer concept. However, there are situations where one could speak of a callback object or a callback interface. Instead of passing the memory address of a function, interface is passed that refers to the location of a function. "
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Example"
},
{
"code": null,
"e": 1138,
"s": 680,
"text": "Let us take an example to understand where callbacks can be used. Suppose a programmer wants to design a tax calculator that calculates total tax of a state. Assume there are only two taxes, central and state tax. Central tax is common whereas the state tax varies from one state to another. The total tax is the sum of the two. Here separate method like stateTax() is implemented for every state and call this method from another method calculateTax() as: "
},
{
"code": null,
"e": 1292,
"s": 1138,
"text": "static void calculateTax(address of stateTax() function)\n{\n ct = 1000.0\n st = calculate state tax depending on the address\n total tax = ct+st;\n}"
},
{
"code": null,
"e": 1653,
"s": 1292,
"text": "In the preceding code, the address of stateTax() is passed to calculateTax(). The calculateTax() method will use that address to call stateTax() method of a particular state and the state tax ‘st’ is calculated. Since the code of stateTax() method changes from one state to another state, it is better to declare it as an abstract method in an interface, as: "
},
{
"code": null,
"e": 1696,
"s": 1653,
"text": "interface STax\n{\n double stateTax();\n}"
},
{
"code": null,
"e": 1766,
"s": 1696,
"text": "The following is the implementation of stateTax() for Punjab state: "
},
{
"code": null,
"e": 1854,
"s": 1766,
"text": "class Punjab implements STax{\n public double stateTax(){\n return 3000.0;\n }\n}"
},
{
"code": null,
"e": 1920,
"s": 1854,
"text": "The following is the implementation of stateTax() for HP state: "
},
{
"code": null,
"e": 2013,
"s": 1920,
"text": "class HP implements STax\n{\n public double stateTax()\n {\n return 1000.0;\n }\n}"
},
{
"code": null,
"e": 2066,
"s": 2013,
"text": "Now, the calculateTax() method can be designed as: "
},
{
"code": null,
"e": 2320,
"s": 2066,
"text": "static void calculateTax(STax t)\n{\n // calculate central tax\n double ct = 2000.0;\n\n // calculate state tax\n double st = t.stateTax();\n double totaltax = st + ct;\n\n // display total tax\n System.out.println(“Total tax =”+totaltax);\n}"
},
{
"code": null,
"e": 2537,
"s": 2320,
"text": "Here, observe the parameter ‘STax t’ in the calculateTax() method. ‘t‘ is a reference of the ‘STax’ interface which is passed as a parameter to the method. Using this reference, the stateTax() method is called, as: "
},
{
"code": null,
"e": 2563,
"s": 2537,
"text": "double st = t.stateTax();"
},
{
"code": null,
"e": 2984,
"s": 2563,
"text": "Here, if ‘t’ refers to stateTax() method of class Punjab, then that method is called and its tax is calculated. Similarly, for class HP. In this way, by passing interface reference to calculateTax() method, it is possible to call stateTax() method of any state. This is called callback mechanism.By passing the interface reference that refers to a method, it is possible to call and use that method from another method. "
},
{
"code": null,
"e": 2989,
"s": 2984,
"text": "Java"
},
{
"code": "// Java program to demonstrate callback mechanism// using interface is Java // Create interfaceimport java.util.Scanner;interface STax { double stateTax();} // Implementation class of Punjab state taxclass Punjab implements STax { public double stateTax() { return 3000.0; }} // Implementation class of Himachal Pradesh state taxclass HP implements STax { public double stateTax() { return 1000.0; }} class TAX { public static void main(String[] args)throws ClassNotFoundException, IllegalAccessException, InstantiationException { Scanner sc = new Scanner(System.in); System.out.println(\"Enter the state name\"); String state = sc.next(); // name of the state // The state name is then stored in an object c Class c = Class.forName(state); // Create the new object of the class whose name is in c // Stax interface reference is now referencing that new object STax ref = (STax)c.newInstance(); /*Call the method to calculate total tax and pass interface reference - this is callback . Here, ref may refer to stateTax() of Punjab or HP classes depending on the class for which the object is created in the previous step */ calculateTax(ref); } static void calculateTax(STax t) { // calculate central tax double ct = 2000.0; // calculate state tax double st = t.stateTax(); double totaltax = st + ct; // display total tax System.out.println(\"Total tax =\" + totaltax); }}",
"e": 4572,
"s": 2989,
"text": null
},
{
"code": null,
"e": 4582,
"s": 4572,
"text": "Output: "
},
{
"code": null,
"e": 4629,
"s": 4582,
"text": "Enter the state name\nPunjab\nTotal tax = 5000.0"
},
{
"code": null,
"e": 4721,
"s": 4629,
"text": "References: How to implement callback functions in Java? Core Java: An Integrated Approach "
},
{
"code": null,
"e": 4748,
"s": 4721,
"text": "sushmakurellageeksforgeeks"
},
{
"code": null,
"e": 4767,
"s": 4748,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4780,
"s": 4767,
"text": "simmytarika5"
},
{
"code": null,
"e": 4796,
"s": 4780,
"text": "java-interfaces"
},
{
"code": null,
"e": 4801,
"s": 4796,
"text": "Java"
},
{
"code": null,
"e": 4806,
"s": 4801,
"text": "Java"
},
{
"code": null,
"e": 4904,
"s": 4806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4955,
"s": 4904,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4986,
"s": 4955,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5005,
"s": 4986,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5035,
"s": 5005,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Collections in Java"
},
{
"code": null,
"e": 5105,
"s": 5073,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5120,
"s": 5105,
"text": "Stream In Java"
},
{
"code": null,
"e": 5132,
"s": 5120,
"text": "Set in Java"
}
]
|
Apache Spark - Installation | Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark.
Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version.
$java -version
If Java is already, installed on your system, you get to see the following response −
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b13)
Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode)
In case you do not have Java installed on your system, then Install Java before proceeding to next step.
You should Scala language to implement Spark. So let us verify Scala installation using following command.
$scala -version
If Scala is already installed on your system, you get to see the following response −
Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL
In case you don’t have Scala installed on your system, then proceed to next step for Scala installation.
Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder.
Follow the below given steps for installing Scala.
Type the following command for extracting the Scala tar file.
$ tar xvf scala-2.11.6.tgz
Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala).
$ su –
Password:
# cd /home/Hadoop/Downloads/
# mv scala-2.11.6 /usr/local/scala
# exit
Use the following command for setting PATH for Scala.
$ export PATH = $PATH:/usr/local/scala/bin
After installation, it is better to verify it. Use the following command for verifying Scala installation.
$scala -version
If Scala is already installed on your system, you get to see the following response −
Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL
Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder.
Follow the steps given below for installing Spark.
The following command for extracting the spark tar file.
$ tar xvf spark-1.3.1-bin-hadoop2.6.tgz
The following commands for moving the Spark software files to respective directory (/usr/local/spark).
$ su –
Password:
# cd /home/Hadoop/Downloads/
# mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark
# exit
Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable.
export PATH=$PATH:/usr/local/spark/bin
Use the following command for sourcing the ~/.bashrc file.
$ source ~/.bashrc
Write the following command for opening Spark shell.
$spark-shell
If spark is installed successfully then you will find the following output.
Spark assembly has been built with Hive, including Datanucleus jars on classpath
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop
15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop
15/06/04 15:25:22 INFO SecurityManager: SecurityManager: authentication disabled;
ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)
15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server
15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292.
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/___/ .__/\_,_/_/ /_/\_\ version 1.4.0
/_/
Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71)
Type in expressions to have them evaluated.
Spark context available as sc
scala>
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1924,
"s": 1771,
"text": "Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark."
},
{
"code": null,
"e": 2048,
"s": 1924,
"text": "Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version."
},
{
"code": null,
"e": 2065,
"s": 2048,
"text": "$java -version \n"
},
{
"code": null,
"e": 2151,
"s": 2065,
"text": "If Java is already, installed on your system, you get to see the following response −"
},
{
"code": null,
"e": 2287,
"s": 2151,
"text": "java version \"1.7.0_71\" \nJava(TM) SE Runtime Environment (build 1.7.0_71-b13) \nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode)\n"
},
{
"code": null,
"e": 2392,
"s": 2287,
"text": "In case you do not have Java installed on your system, then Install Java before proceeding to next step."
},
{
"code": null,
"e": 2499,
"s": 2392,
"text": "You should Scala language to implement Spark. So let us verify Scala installation using following command."
},
{
"code": null,
"e": 2516,
"s": 2499,
"text": "$scala -version\n"
},
{
"code": null,
"e": 2602,
"s": 2516,
"text": "If Scala is already installed on your system, you get to see the following response −"
},
{
"code": null,
"e": 2670,
"s": 2602,
"text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n"
},
{
"code": null,
"e": 2775,
"s": 2670,
"text": "In case you don’t have Scala installed on your system, then proceed to next step for Scala installation."
},
{
"code": null,
"e": 2986,
"s": 2775,
"text": "Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder."
},
{
"code": null,
"e": 3037,
"s": 2986,
"text": "Follow the below given steps for installing Scala."
},
{
"code": null,
"e": 3099,
"s": 3037,
"text": "Type the following command for extracting the Scala tar file."
},
{
"code": null,
"e": 3127,
"s": 3099,
"text": "$ tar xvf scala-2.11.6.tgz\n"
},
{
"code": null,
"e": 3235,
"s": 3127,
"text": "Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala)."
},
{
"code": null,
"e": 3329,
"s": 3235,
"text": "$ su – \nPassword: \n# cd /home/Hadoop/Downloads/ \n# mv scala-2.11.6 /usr/local/scala \n# exit \n"
},
{
"code": null,
"e": 3383,
"s": 3329,
"text": "Use the following command for setting PATH for Scala."
},
{
"code": null,
"e": 3427,
"s": 3383,
"text": "$ export PATH = $PATH:/usr/local/scala/bin\n"
},
{
"code": null,
"e": 3534,
"s": 3427,
"text": "After installation, it is better to verify it. Use the following command for verifying Scala installation."
},
{
"code": null,
"e": 3551,
"s": 3534,
"text": "$scala -version\n"
},
{
"code": null,
"e": 3637,
"s": 3551,
"text": "If Scala is already installed on your system, you get to see the following response −"
},
{
"code": null,
"e": 3705,
"s": 3637,
"text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n"
},
{
"code": null,
"e": 3935,
"s": 3705,
"text": "Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder."
},
{
"code": null,
"e": 3986,
"s": 3935,
"text": "Follow the steps given below for installing Spark."
},
{
"code": null,
"e": 4043,
"s": 3986,
"text": "The following command for extracting the spark tar file."
},
{
"code": null,
"e": 4085,
"s": 4043,
"text": "$ tar xvf spark-1.3.1-bin-hadoop2.6.tgz \n"
},
{
"code": null,
"e": 4188,
"s": 4085,
"text": "The following commands for moving the Spark software files to respective directory (/usr/local/spark)."
},
{
"code": null,
"e": 4297,
"s": 4188,
"text": "$ su – \nPassword: \n\n# cd /home/Hadoop/Downloads/ \n# mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark \n# exit \n"
},
{
"code": null,
"e": 4433,
"s": 4297,
"text": "Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable."
},
{
"code": null,
"e": 4473,
"s": 4433,
"text": "export PATH=$PATH:/usr/local/spark/bin\n"
},
{
"code": null,
"e": 4532,
"s": 4473,
"text": "Use the following command for sourcing the ~/.bashrc file."
},
{
"code": null,
"e": 4552,
"s": 4532,
"text": "$ source ~/.bashrc\n"
},
{
"code": null,
"e": 4605,
"s": 4552,
"text": "Write the following command for opening Spark shell."
},
{
"code": null,
"e": 4619,
"s": 4605,
"text": "$spark-shell\n"
},
{
"code": null,
"e": 4695,
"s": 4619,
"text": "If spark is installed successfully then you will find the following output."
},
{
"code": null,
"e": 5667,
"s": 4695,
"text": "Spark assembly has been built with Hive, including Datanucleus jars on classpath \nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties \n15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop \n15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop\n15/06/04 15:25:22 INFO SecurityManager: SecurityManager: authentication disabled;\n ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop) \n15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server \n15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292. \nWelcome to \n ____ __ \n / __/__ ___ _____/ /__ \n _\\ \\/ _ \\/ _ `/ __/ '_/ \n /___/ .__/\\_,_/_/ /_/\\_\\ version 1.4.0 \n /_/ \n\t\t\nUsing Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71) \nType in expressions to have them evaluated. \nSpark context available as sc \nscala> \n"
},
{
"code": null,
"e": 5702,
"s": 5667,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5721,
"s": 5702,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5756,
"s": 5721,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5777,
"s": 5756,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5810,
"s": 5777,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5823,
"s": 5810,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5858,
"s": 5823,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5876,
"s": 5858,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5909,
"s": 5876,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5927,
"s": 5909,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5960,
"s": 5927,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5978,
"s": 5960,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5985,
"s": 5978,
"text": " Print"
},
{
"code": null,
"e": 5996,
"s": 5985,
"text": " Add Notes"
}
]
|
WAP - WML Script | WMLScript (Wireless Markup Language Script) is the client-side scripting language of WML (Wireless Markup Language). A scripting language is similar to a programming language, but is of lighter weight. With WMLScript, the wireless device can do some of the processing and computation. This reduces the number of requests and responses to/from the server.
This chapter will give brief description of all the important WML Script components.
WML Script is very similar to Java Script. WML Script components have almost similar meaning as they have in Java Script. The WML Script program components are summarized here.
WML Script supports following type of operators.
Arithmetic Operators
Arithmetic Operators
Comparison Operators
Comparison Operators
Logical (or Relational) Operators
Logical (or Relational) Operators
Assignment Operators
Assignment Operators
Conditional (or ternary) Operators
Conditional (or ternary) Operators
Check for complete detail of The WML Operators.
Control statements are used for controlling the sequence and iterations in a program.
Check for complete detail of WML Script Control Statements.
The user-defined functions are declared in a separate file having the extension .wmls. Functions are declared as follows −
function name (parameters) {
control statements;
return var;
}
The functions used are stored in a separate file with the extension .wmls. The functions are called as the filename followed by a hash, followed by the function name −
maths.wmls#squar()
The are six standard libraries totally. Here is an overview of them −
Lang − The Lang library provides functions related to the WMLScript language core.
Example Function − abs(),abort(), characterSet(),float(), isFloat(), isInt(), max(), isMax(), min(), minInt(), maxInt(), parseFloat(), parseInt(), random(), seed()
Lang − The Lang library provides functions related to the WMLScript language core.
Example Function − abs(),abort(), characterSet(),float(), isFloat(), isInt(), max(), isMax(), min(), minInt(), maxInt(), parseFloat(), parseInt(), random(), seed()
Float − The Float library contains functions that help us perform floating-point arithmetic operations.
Example Function − sqrt(), round(), pow(), ceil(), floor(), int(), maxFloat(), minFloat()
Float − The Float library contains functions that help us perform floating-point arithmetic operations.
Example Function − sqrt(), round(), pow(), ceil(), floor(), int(), maxFloat(), minFloat()
String − The String library provides a number of functions that help us manipulate strings.
Example Function − length(), charAt(), find(), replace(), trim(), compare(), format(), isEmpty(), squeeze(), toString(), elementAt(), elements(), insertAt(), removeAt(), replaceAt()
String − The String library provides a number of functions that help us manipulate strings.
Example Function − length(), charAt(), find(), replace(), trim(), compare(), format(), isEmpty(), squeeze(), toString(), elementAt(), elements(), insertAt(), removeAt(), replaceAt()
URL − The URL library contains functions that help us manipulate URLs.
Example Function − getPath(), getReferer(), getHost(), getBase(), escapeString(), isValid(), loadString(), resolve(), unescapeString(), getFragment()
URL − The URL library contains functions that help us manipulate URLs.
Example Function − getPath(), getReferer(), getHost(), getBase(), escapeString(), isValid(), loadString(), resolve(), unescapeString(), getFragment()
WMLBrowser − The WMLBrowser library provides a group of functions to control the WML browser or to get information from it.
Example Function − go(), prev(), next(), getCurrentCard(), refresh(), getVar(), setVar()
WMLBrowser − The WMLBrowser library provides a group of functions to control the WML browser or to get information from it.
Example Function − go(), prev(), next(), getCurrentCard(), refresh(), getVar(), setVar()
Dialogs − The Dialogs library Contains the user interface functions.
Example Function − prompt(), confirm(), alert()
Dialogs − The Dialogs library Contains the user interface functions.
Example Function − prompt(), confirm(), alert()
There are two types of comments in WMLScript −
Single-line comment − To add a single-line comment, begin a line of text with the // characters.
Single-line comment − To add a single-line comment, begin a line of text with the // characters.
Multi-line comment − To add a multi-line comment, enclose the text within /* and */.
Multi-line comment − To add a multi-line comment, enclose the text within /* and */.
These rules are the same in WMLScript, JavaScript, Java, and C++. The WMLScript engine will ignore all comments. The following WMLScript example demonstrates the use of comments −
// This is a single-line comment.
/* This is a multi-line comment. */
/* A multi-line comment can be placed on a single line. */
The WMLScript language is case-sensitive. For example, a WMLScript function with the name WMLScript Function is different from wmlscript function. So, be careful of the capitalization when defining or referring to a function or a variable in WMLScript.
Except in string literals, WMLScript ignores extra whitespaces like spaces, tabs, and
newlines.
A semicolon is required to end a statement in WMLScript. This is the same as C++ and Java. Note that JavaScript does not have such requirement but WML Script makes it mandatory.
28 Lectures
4 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2158,
"s": 1803,
"text": "WMLScript (Wireless Markup Language Script) is the client-side scripting language of WML (Wireless Markup Language). A scripting language is similar to a programming language, but is of lighter weight. With WMLScript, the wireless device can do some of the processing and computation. This reduces the number of requests and responses to/from the server."
},
{
"code": null,
"e": 2243,
"s": 2158,
"text": "This chapter will give brief description of all the important WML Script components."
},
{
"code": null,
"e": 2420,
"s": 2243,
"text": "WML Script is very similar to Java Script. WML Script components have almost similar meaning as they have in Java Script. The WML Script program components are summarized here."
},
{
"code": null,
"e": 2469,
"s": 2420,
"text": "WML Script supports following type of operators."
},
{
"code": null,
"e": 2490,
"s": 2469,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2511,
"s": 2490,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2532,
"s": 2511,
"text": "Comparison Operators"
},
{
"code": null,
"e": 2553,
"s": 2532,
"text": "Comparison Operators"
},
{
"code": null,
"e": 2587,
"s": 2553,
"text": "Logical (or Relational) Operators"
},
{
"code": null,
"e": 2621,
"s": 2587,
"text": "Logical (or Relational) Operators"
},
{
"code": null,
"e": 2642,
"s": 2621,
"text": "Assignment Operators"
},
{
"code": null,
"e": 2663,
"s": 2642,
"text": "Assignment Operators"
},
{
"code": null,
"e": 2698,
"s": 2663,
"text": "Conditional (or ternary) Operators"
},
{
"code": null,
"e": 2733,
"s": 2698,
"text": "Conditional (or ternary) Operators"
},
{
"code": null,
"e": 2781,
"s": 2733,
"text": "Check for complete detail of The WML Operators."
},
{
"code": null,
"e": 2867,
"s": 2781,
"text": "Control statements are used for controlling the sequence and iterations in a program."
},
{
"code": null,
"e": 2927,
"s": 2867,
"text": "Check for complete detail of WML Script Control Statements."
},
{
"code": null,
"e": 3050,
"s": 2927,
"text": "The user-defined functions are declared in a separate file having the extension .wmls. Functions are declared as follows −"
},
{
"code": null,
"e": 3122,
"s": 3050,
"text": "function name (parameters) { \n control statements;\n return var;\n}"
},
{
"code": null,
"e": 3290,
"s": 3122,
"text": "The functions used are stored in a separate file with the extension .wmls. The functions are called as the filename followed by a hash, followed by the function name −"
},
{
"code": null,
"e": 3309,
"s": 3290,
"text": "maths.wmls#squar()"
},
{
"code": null,
"e": 3379,
"s": 3309,
"text": "The are six standard libraries totally. Here is an overview of them −"
},
{
"code": null,
"e": 3626,
"s": 3379,
"text": "Lang − The Lang library provides functions related to the WMLScript language core.\nExample Function − abs(),abort(), characterSet(),float(), isFloat(), isInt(), max(), isMax(), min(), minInt(), maxInt(), parseFloat(), parseInt(), random(), seed()"
},
{
"code": null,
"e": 3709,
"s": 3626,
"text": "Lang − The Lang library provides functions related to the WMLScript language core."
},
{
"code": null,
"e": 3873,
"s": 3709,
"text": "Example Function − abs(),abort(), characterSet(),float(), isFloat(), isInt(), max(), isMax(), min(), minInt(), maxInt(), parseFloat(), parseInt(), random(), seed()"
},
{
"code": null,
"e": 4067,
"s": 3873,
"text": "Float − The Float library contains functions that help us perform floating-point arithmetic operations.\nExample Function − sqrt(), round(), pow(), ceil(), floor(), int(), maxFloat(), minFloat()"
},
{
"code": null,
"e": 4171,
"s": 4067,
"text": "Float − The Float library contains functions that help us perform floating-point arithmetic operations."
},
{
"code": null,
"e": 4261,
"s": 4171,
"text": "Example Function − sqrt(), round(), pow(), ceil(), floor(), int(), maxFloat(), minFloat()"
},
{
"code": null,
"e": 4535,
"s": 4261,
"text": "String − The String library provides a number of functions that help us manipulate strings.\nExample Function − length(), charAt(), find(), replace(), trim(), compare(), format(), isEmpty(), squeeze(), toString(), elementAt(), elements(), insertAt(), removeAt(), replaceAt()"
},
{
"code": null,
"e": 4627,
"s": 4535,
"text": "String − The String library provides a number of functions that help us manipulate strings."
},
{
"code": null,
"e": 4809,
"s": 4627,
"text": "Example Function − length(), charAt(), find(), replace(), trim(), compare(), format(), isEmpty(), squeeze(), toString(), elementAt(), elements(), insertAt(), removeAt(), replaceAt()"
},
{
"code": null,
"e": 5030,
"s": 4809,
"text": "URL − The URL library contains functions that help us manipulate URLs.\nExample Function − getPath(), getReferer(), getHost(), getBase(), escapeString(), isValid(), loadString(), resolve(), unescapeString(), getFragment()"
},
{
"code": null,
"e": 5101,
"s": 5030,
"text": "URL − The URL library contains functions that help us manipulate URLs."
},
{
"code": null,
"e": 5251,
"s": 5101,
"text": "Example Function − getPath(), getReferer(), getHost(), getBase(), escapeString(), isValid(), loadString(), resolve(), unescapeString(), getFragment()"
},
{
"code": null,
"e": 5464,
"s": 5251,
"text": "WMLBrowser − The WMLBrowser library provides a group of functions to control the WML browser or to get information from it.\nExample Function − go(), prev(), next(), getCurrentCard(), refresh(), getVar(), setVar()"
},
{
"code": null,
"e": 5588,
"s": 5464,
"text": "WMLBrowser − The WMLBrowser library provides a group of functions to control the WML browser or to get information from it."
},
{
"code": null,
"e": 5677,
"s": 5588,
"text": "Example Function − go(), prev(), next(), getCurrentCard(), refresh(), getVar(), setVar()"
},
{
"code": null,
"e": 5794,
"s": 5677,
"text": "Dialogs − The Dialogs library Contains the user interface functions.\nExample Function − prompt(), confirm(), alert()"
},
{
"code": null,
"e": 5863,
"s": 5794,
"text": "Dialogs − The Dialogs library Contains the user interface functions."
},
{
"code": null,
"e": 5911,
"s": 5863,
"text": "Example Function − prompt(), confirm(), alert()"
},
{
"code": null,
"e": 5958,
"s": 5911,
"text": "There are two types of comments in WMLScript −"
},
{
"code": null,
"e": 6056,
"s": 5958,
"text": "Single-line comment − To add a single-line comment, begin a line of text with the // characters. "
},
{
"code": null,
"e": 6154,
"s": 6056,
"text": "Single-line comment − To add a single-line comment, begin a line of text with the // characters. "
},
{
"code": null,
"e": 6239,
"s": 6154,
"text": "Multi-line comment − To add a multi-line comment, enclose the text within /* and */."
},
{
"code": null,
"e": 6324,
"s": 6239,
"text": "Multi-line comment − To add a multi-line comment, enclose the text within /* and */."
},
{
"code": null,
"e": 6504,
"s": 6324,
"text": "These rules are the same in WMLScript, JavaScript, Java, and C++. The WMLScript engine will ignore all comments. The following WMLScript example demonstrates the use of comments −"
},
{
"code": null,
"e": 6635,
"s": 6504,
"text": "// This is a single-line comment.\n\n/* This is a multi-line comment. */\n\n/* A multi-line comment can be placed on a single line. */"
},
{
"code": null,
"e": 6888,
"s": 6635,
"text": "The WMLScript language is case-sensitive. For example, a WMLScript function with the name WMLScript Function is different from wmlscript function. So, be careful of the capitalization when defining or referring to a function or a variable in WMLScript."
},
{
"code": null,
"e": 6984,
"s": 6888,
"text": "Except in string literals, WMLScript ignores extra whitespaces like spaces, tabs, and\nnewlines."
},
{
"code": null,
"e": 7162,
"s": 6984,
"text": "A semicolon is required to end a statement in WMLScript. This is the same as C++ and Java. Note that JavaScript does not have such requirement but WML Script makes it mandatory."
},
{
"code": null,
"e": 7195,
"s": 7162,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7212,
"s": 7195,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7219,
"s": 7212,
"text": " Print"
},
{
"code": null,
"e": 7230,
"s": 7219,
"text": " Add Notes"
}
]
|
How to know if two arrays have the same values in JavaScript? | Let’s say the following are our arrays −
var firstArray=[100,200,400];
var secondArray=[400,100,200];
You can sort both the arrays using the sort() method and use for loop to compare each value as in the below code −
var firstArray=[100,200,400];
var secondArray=[400,100,200];
function areBothArraysEqual(firstArray, secondArray) {
if (!Array.isArray(firstArray) || ! Array.isArray(secondArray) ||
firstArray.length !== secondArray.length)
return false;
var tempFirstArray = firstArray.concat().sort();
var tempSecondArray = secondArray.concat().sort();
for (var i = 0; i < tempFirstArray.length; i++) {
if (tempFirstArray[i] !== tempSecondArray[i])
return false;
}
return true;
}
if(areBothArraysEqual(firstArray,secondArray))
console.log("Both are equals");
else
console.log("Both are not equals");
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo156.js.
PS C:\Users\Amit\JavaScript-code> node demo156.js
Both are equals | [
{
"code": null,
"e": 1103,
"s": 1062,
"text": "Let’s say the following are our arrays −"
},
{
"code": null,
"e": 1164,
"s": 1103,
"text": "var firstArray=[100,200,400];\nvar secondArray=[400,100,200];"
},
{
"code": null,
"e": 1279,
"s": 1164,
"text": "You can sort both the arrays using the sort() method and use for loop to compare each value as in the below code −"
},
{
"code": null,
"e": 1903,
"s": 1279,
"text": "var firstArray=[100,200,400];\nvar secondArray=[400,100,200];\nfunction areBothArraysEqual(firstArray, secondArray) {\n if (!Array.isArray(firstArray) || ! Array.isArray(secondArray) ||\n firstArray.length !== secondArray.length)\n return false;\n var tempFirstArray = firstArray.concat().sort();\n var tempSecondArray = secondArray.concat().sort();\n for (var i = 0; i < tempFirstArray.length; i++) {\n if (tempFirstArray[i] !== tempSecondArray[i])\n return false;\n }\n return true;\n}\nif(areBothArraysEqual(firstArray,secondArray))\nconsole.log(\"Both are equals\");\nelse\nconsole.log(\"Both are not equals\");"
},
{
"code": null,
"e": 1969,
"s": 1903,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1987,
"s": 1969,
"text": "node fileName.js."
},
{
"code": null,
"e": 2021,
"s": 1987,
"text": "Here, my file name is demo156.js."
},
{
"code": null,
"e": 2087,
"s": 2021,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo156.js\nBoth are equals"
}
]
|
Java - Basic Operators | Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
Show Examples
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Following are the assignment operators supported by Java language −
Show Examples
There are few other operators supported by Java Language.
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Following is an example −
Example
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This will produce the following result −
Output
Value of b is : 30
Value of b is : 20
This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example −
Example
public class Test {
public static void main(String args[]) {
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
This will produce the following result −
Output
true
This operator will still return true, if the object being compared is the assignment compatible with the type on the right. Following is one more example −
Example
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]) {
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
This will produce the following result −
Output
true
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
The next chapter will explain about loop control in Java programming. The chapter will describe various types of loops and how these loops can be used in Java program development and for what purposes they are being used.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2505,
"s": 2377,
"text": "Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −"
},
{
"code": null,
"e": 2526,
"s": 2505,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 2547,
"s": 2526,
"text": "Relational Operators"
},
{
"code": null,
"e": 2565,
"s": 2547,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 2583,
"s": 2565,
"text": "Logical Operators"
},
{
"code": null,
"e": 2604,
"s": 2583,
"text": "Assignment Operators"
},
{
"code": null,
"e": 2619,
"s": 2604,
"text": "Misc Operators"
},
{
"code": null,
"e": 2777,
"s": 2619,
"text": "Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −"
},
{
"code": null,
"e": 2844,
"s": 2777,
"text": "Assume integer variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2858,
"s": 2844,
"text": "Show Examples"
},
{
"code": null,
"e": 2927,
"s": 2858,
"text": "There are following relational operators supported by Java language."
},
{
"code": null,
"e": 2986,
"s": 2927,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 3000,
"s": 2986,
"text": "Show Examples"
},
{
"code": null,
"e": 3117,
"s": 3000,
"text": "Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte."
},
{
"code": null,
"e": 3259,
"s": 3117,
"text": "Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −"
},
{
"code": null,
"e": 3273,
"s": 3259,
"text": "a = 0011 1100"
},
{
"code": null,
"e": 3287,
"s": 3273,
"text": "b = 0000 1101"
},
{
"code": null,
"e": 3305,
"s": 3287,
"text": "-----------------"
},
{
"code": null,
"e": 3321,
"s": 3305,
"text": "a&b = 0000 1100"
},
{
"code": null,
"e": 3337,
"s": 3321,
"text": "a|b = 0011 1101"
},
{
"code": null,
"e": 3353,
"s": 3337,
"text": "a^b = 0011 0001"
},
{
"code": null,
"e": 3369,
"s": 3353,
"text": "~a = 1100 0011"
},
{
"code": null,
"e": 3419,
"s": 3369,
"text": "The following table lists the bitwise operators −"
},
{
"code": null,
"e": 3485,
"s": 3419,
"text": "Assume integer variable A holds 60 and variable B holds 13 then −"
},
{
"code": null,
"e": 3499,
"s": 3485,
"text": "Show Examples"
},
{
"code": null,
"e": 3549,
"s": 3499,
"text": "The following table lists the logical operators −"
},
{
"code": null,
"e": 3622,
"s": 3549,
"text": "Assume Boolean variables A holds true and variable B holds false, then −"
},
{
"code": null,
"e": 3636,
"s": 3622,
"text": "Show Examples"
},
{
"code": null,
"e": 3704,
"s": 3636,
"text": "Following are the assignment operators supported by Java language −"
},
{
"code": null,
"e": 3718,
"s": 3704,
"text": "Show Examples"
},
{
"code": null,
"e": 3776,
"s": 3718,
"text": "There are few other operators supported by Java Language."
},
{
"code": null,
"e": 4038,
"s": 3776,
"text": "Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −"
},
{
"code": null,
"e": 4098,
"s": 4038,
"text": "variable x = (expression) ? value if true : value if false\n"
},
{
"code": null,
"e": 4124,
"s": 4098,
"text": "Following is an example −"
},
{
"code": null,
"e": 4132,
"s": 4124,
"text": "Example"
},
{
"code": null,
"e": 4399,
"s": 4132,
"text": "public class Test {\n\n public static void main(String args[]) {\n int a, b;\n a = 10;\n b = (a == 1) ? 20: 30;\n System.out.println( \"Value of b is : \" + b );\n\n b = (a == 10) ? 20: 30;\n System.out.println( \"Value of b is : \" + b );\n }\n}"
},
{
"code": null,
"e": 4440,
"s": 4399,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4447,
"s": 4440,
"text": "Output"
},
{
"code": null,
"e": 4486,
"s": 4447,
"text": "Value of b is : 30\nValue of b is : 20\n"
},
{
"code": null,
"e": 4676,
"s": 4486,
"text": "This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as −"
},
{
"code": null,
"e": 4742,
"s": 4676,
"text": "( Object reference variable ) instanceof (class/interface type)\n"
},
{
"code": null,
"e": 4940,
"s": 4742,
"text": "If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example −"
},
{
"code": null,
"e": 4948,
"s": 4940,
"text": "Example"
},
{
"code": null,
"e": 5199,
"s": 4948,
"text": "public class Test {\n\n public static void main(String args[]) {\n\n String name = \"James\";\n\n // following will return true since name is type of String\n boolean result = name instanceof String;\n System.out.println( result );\n }\n}"
},
{
"code": null,
"e": 5240,
"s": 5199,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5247,
"s": 5240,
"text": "Output"
},
{
"code": null,
"e": 5253,
"s": 5247,
"text": "true\n"
},
{
"code": null,
"e": 5409,
"s": 5253,
"text": "This operator will still return true, if the object being compared is the assignment compatible with the type on the right. Following is one more example −"
},
{
"code": null,
"e": 5417,
"s": 5409,
"text": "Example"
},
{
"code": null,
"e": 5630,
"s": 5417,
"text": "class Vehicle {}\n\npublic class Car extends Vehicle {\n\n public static void main(String args[]) {\n\n Vehicle a = new Car();\n boolean result = a instanceof Car;\n System.out.println( result );\n }\n}"
},
{
"code": null,
"e": 5671,
"s": 5630,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5678,
"s": 5671,
"text": "Output"
},
{
"code": null,
"e": 5684,
"s": 5678,
"text": "true\n"
},
{
"code": null,
"e": 5946,
"s": 5684,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −"
},
{
"code": null,
"e": 6114,
"s": 5946,
"text": "For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7."
},
{
"code": null,
"e": 6309,
"s": 6114,
"text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first."
},
{
"code": null,
"e": 6531,
"s": 6309,
"text": "The next chapter will explain about loop control in Java programming. The chapter will describe various types of loops and how these loops can be used in Java program development and for what purposes they are being used."
},
{
"code": null,
"e": 6564,
"s": 6531,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6580,
"s": 6564,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6613,
"s": 6580,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6629,
"s": 6613,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6664,
"s": 6629,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6678,
"s": 6664,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6712,
"s": 6678,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6726,
"s": 6712,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6763,
"s": 6726,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6778,
"s": 6763,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6811,
"s": 6778,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6830,
"s": 6811,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6837,
"s": 6830,
"text": " Print"
},
{
"code": null,
"e": 6848,
"s": 6837,
"text": " Add Notes"
}
]
|
Tryit Editor v3.7 | Tryit: Get current position | []
|
Extracting Relations Among Entities Using NLP | by Arun Jagota | Towards Data Science | In this post, we introduce the problem of extracting relations among named entities using NLP. We illustrate this problem with examples of progressively increasing sophistication, and muse, along the way, on ideas towards solving them.
Let’s get started.
Consider these sentences.
John Doe works at Google.Apple is located in Cupertino.
We’d like to detect the various entities in these sentences. Them being
Person name = John DoeCompany = GoogleCompany = AppleCity = Cupertino
Fortunately, the NLP of this task (named entity recognition) has matured enough so that this can be done with high quality. See [1].
A logical next step is to be able to deduce the relationships among these entities using NLP. In our case, we hope to get
works_at(person:john doe,company:google)located_in(company:apple, city:cupertino)
Clearly automating the process of detecting not only the entities but the relations among them has considerable value. Using this approach we can extract structured data from unstructured documents (of which there are plenty). Powerful queries can then be performed on the structured data. For example to power question-answering systems.
There are numerous particular applications of this meta use-case. Such as mining documents in specific verticals to uncover entities and relationships among them in that vertical. Similarly, mining documents in a company to uncover what's happening under the hood in its engineering or business processes.
First Observations
Let’s look closely at our sentences. The relations of interest are embedded within works at and is located in. Seems like we should be able to detect these using NLP somehow. Let’s give this problem a name: relational phrase extraction.
We did a part-of-speech analysis of this sentence, at https://parts-of-speech.info/
As we see, the POS tags carry strong signals towards identifying the relational phrases. Also keep in mind that named entity recognition would have already tagged the named entities in these sentences which would additionally strengthen our confidence that, in these examples, the relational phrases correspond to the sequence of POS-tags <verb> <preposition>.
To bring this out more vividly, let’s depict the tokenized sentences along with their tagged sequences as below.
Tokens: John Doe works at GooglePOS tags: noun noun verb preposition nounNER tags: person person — — companyTokens: Apple is located in CupertinoPOS tags: noun verb verb preposition nounNER tags: company — — — city
Clearly, in these examples, combining the information in the POS tags with those in the NER tags works well to identify the relational phrases.
A more elaborate example
Next, consider this sentence, taken from [2].
Read The Adventures of Sherlock Holmes by Arthur Conan Doyle online or in your email
The named entities are The Adventures of Sherlock Holmes, a book title, and Arthur Conan Doyle, a person’s name. The former is harder to recognize than the latter. This is because book titles are longer and have a more diverse universe. Interestingly, this book title has a person’s name in it.
For now, let’s bury the complexity of recognizing book titles under the hood. If you are curious, read up on some of the more elaborate approaches such as HMMs in the context of NER in [1].
Assuming the two entities are recognized correctly, we notice that the relational phrase still sits between them. That is, this sentence has the structure
<words> book-title by person-name <words>
Below is the POS analysis of the relevant portion of this sentence.
That the word by sandwiched between the entities is a preposition is assuring. It supports forming the relational phrase from this by.
Let’s use this opportunity to ‘dig’ into by a bit more. It's easy to imagine that in a huge corpus we may come across numerous instances of
book-title by person-name
From these instances, we will be able to also infer that the book title always precedes the by and that the person's name always follows it. Thus in principle, the word by can be used as an additional predictor of the entities themselves, in our case the book’s title and the person’s name. Consider replacing by with written by. The predictive strength of the latter towards the book title and person name entities is now higher.
Next, let’s look at
Wimbledon is a tennis tournament held in the UK in the first two weeks of July every year.
This one could be ‘parsed’ via entity recognition (somewhat broadly interpreted) as
Sports event name is a sport tournament held in the location in the time.
The first three entities are reasonably crisp and can be detected via NER approaches suitably trained. The fourth one, time, is less crisp. In our example, its value is first two weeks of July every year. It might be difficult to train a NER for this less crisp entity. Instead, we might consider recognizing more granular time-based entities. Such as month. Armed with such a detector we have a partial inference of in the time as in month: July.
Let’s now look at location. It makes sense to treat it in a hierarchical fashion. Specifically, to break location down into finer entities such as country, state, city, ... We can then recognize each of these entities and use a taxonomy to relate them. Such as country is-a location, state is-a location, state is-in country, etc.(Note that a particular state may be in multiple is-in associations with countries.)
Okay, now that we have discussed the entities, what relationships can we infer among them? Definitely the is-a relationship below.
Sports event name is-a sport tournament
The other ones need more thought. First, for convenience, let’s abbreviate the sentence with entity variables in it as below.
SEN is a ST held in the L in the T.
In our example, we see that ST held-in L would be a wrong inference. It is SEN=Wimbledon that is held in L=UK, not ST=tennis tournament?
An idea worth exploring is to start by forming three hypotheses, expressed in the form of association rules [3]
ST=tennis tournament, held-in ⇒ L=UKSEN=Wimbledon, held-in ⇒ L=UKSEN=Wimbledon, ST=tennis tournament, held-in ⇒ L=UK
In the above, think of X ⇒ Y as
IF X THEN Y
Given a huge corpus, such as Wikipedia, broken down into individual sentences, we can then compute the so-called supports and confidences of each of these association rules. The support of a rule X ⇒ Y is the number of sentences in which X holds. The confidence of this rule is P(Y|X).
From such an analysis we can reasonably expect to infer that ST=tennis tournament does not imply that it is held in the UK whereas SEN=Wimbledon always implies that it is held in the UK.
Next, consider the in relation involving T (time). We can treat it similarly. Our set of candidate association rules is a bit larger. In X ⇒ Y, Y is always T = first two weeks of July every year. X is any nonempty subset of {SEN=Wimbledon, ST=tennis tournament, L=UK}
Framing this problem as one involving mining for high-confidence association rules lets us use highly scalable algorithms that have been developed for this problem. Such as FP growth or the A’priori algorithm. See [3]. We may indeed confront scale if we are going to do this analysis on all sentences in Wikipedia, many having more than two entities in them (as does ours).
Finally, let’s turn our attention to the following sentence.
In 2019, the men’s singles winner was Novak Djokovic who defeated Roger Federer in the longest singles final in Wimbledon history.
This sentence is a good one to illustrate going beyond relating the entities that occur in the sentence from its contents alone. Rather, we will infer (or more accurately, collect evidence for) relationships that may be inferred from combining the information in this sentence with a suitable global knowledge model.
We won’t actually specify the knowledge model’s form. Rather we will muse on what we might be able to infer from the information in this sentence were we to also have access to such a model.
From
Novak Djokovic who defeated Roger Federer
we can extract
defeated(Person Name: Novak Dkokovic, Person Name: Roger Federer)
in the manner discussed earlier.
Now consider the word Wimbledon that appears in the same sentence later on. Assume its been correctly recognized as Sports Event Name. We may now be able to link these person names to this event. If so, and assuming our knowledge graph knows that Wimbledon is a tennis event, we can also infer that Novak Dkokovic and Roger Federer are tennis players.
We are listing the inferences in the last sentence of the previous paragraph mainly to illustrate what sorts of things we can deduce. For these particular assertions — that these people are tennis players — there may be stronger, more direct, evidence in other sentences in Wikipedia.
Finally, let’s note that we can even infer the genders of these persons from their first names alone. The mention of men’s earlier in the sentence may then be seen as corroborating evidence. | [
{
"code": null,
"e": 407,
"s": 171,
"text": "In this post, we introduce the problem of extracting relations among named entities using NLP. We illustrate this problem with examples of progressively increasing sophistication, and muse, along the way, on ideas towards solving them."
},
{
"code": null,
"e": 426,
"s": 407,
"text": "Let’s get started."
},
{
"code": null,
"e": 452,
"s": 426,
"text": "Consider these sentences."
},
{
"code": null,
"e": 508,
"s": 452,
"text": "John Doe works at Google.Apple is located in Cupertino."
},
{
"code": null,
"e": 580,
"s": 508,
"text": "We’d like to detect the various entities in these sentences. Them being"
},
{
"code": null,
"e": 650,
"s": 580,
"text": "Person name = John DoeCompany = GoogleCompany = AppleCity = Cupertino"
},
{
"code": null,
"e": 783,
"s": 650,
"text": "Fortunately, the NLP of this task (named entity recognition) has matured enough so that this can be done with high quality. See [1]."
},
{
"code": null,
"e": 905,
"s": 783,
"text": "A logical next step is to be able to deduce the relationships among these entities using NLP. In our case, we hope to get"
},
{
"code": null,
"e": 987,
"s": 905,
"text": "works_at(person:john doe,company:google)located_in(company:apple, city:cupertino)"
},
{
"code": null,
"e": 1326,
"s": 987,
"text": "Clearly automating the process of detecting not only the entities but the relations among them has considerable value. Using this approach we can extract structured data from unstructured documents (of which there are plenty). Powerful queries can then be performed on the structured data. For example to power question-answering systems."
},
{
"code": null,
"e": 1632,
"s": 1326,
"text": "There are numerous particular applications of this meta use-case. Such as mining documents in specific verticals to uncover entities and relationships among them in that vertical. Similarly, mining documents in a company to uncover what's happening under the hood in its engineering or business processes."
},
{
"code": null,
"e": 1651,
"s": 1632,
"text": "First Observations"
},
{
"code": null,
"e": 1888,
"s": 1651,
"text": "Let’s look closely at our sentences. The relations of interest are embedded within works at and is located in. Seems like we should be able to detect these using NLP somehow. Let’s give this problem a name: relational phrase extraction."
},
{
"code": null,
"e": 1972,
"s": 1888,
"text": "We did a part-of-speech analysis of this sentence, at https://parts-of-speech.info/"
},
{
"code": null,
"e": 2333,
"s": 1972,
"text": "As we see, the POS tags carry strong signals towards identifying the relational phrases. Also keep in mind that named entity recognition would have already tagged the named entities in these sentences which would additionally strengthen our confidence that, in these examples, the relational phrases correspond to the sequence of POS-tags <verb> <preposition>."
},
{
"code": null,
"e": 2446,
"s": 2333,
"text": "To bring this out more vividly, let’s depict the tokenized sentences along with their tagged sequences as below."
},
{
"code": null,
"e": 2739,
"s": 2446,
"text": "Tokens: John Doe works at GooglePOS tags: noun noun verb preposition nounNER tags: person person — — companyTokens: Apple is located in CupertinoPOS tags: noun verb verb preposition nounNER tags: company — — — city"
},
{
"code": null,
"e": 2883,
"s": 2739,
"text": "Clearly, in these examples, combining the information in the POS tags with those in the NER tags works well to identify the relational phrases."
},
{
"code": null,
"e": 2908,
"s": 2883,
"text": "A more elaborate example"
},
{
"code": null,
"e": 2954,
"s": 2908,
"text": "Next, consider this sentence, taken from [2]."
},
{
"code": null,
"e": 3039,
"s": 2954,
"text": "Read The Adventures of Sherlock Holmes by Arthur Conan Doyle online or in your email"
},
{
"code": null,
"e": 3334,
"s": 3039,
"text": "The named entities are The Adventures of Sherlock Holmes, a book title, and Arthur Conan Doyle, a person’s name. The former is harder to recognize than the latter. This is because book titles are longer and have a more diverse universe. Interestingly, this book title has a person’s name in it."
},
{
"code": null,
"e": 3524,
"s": 3334,
"text": "For now, let’s bury the complexity of recognizing book titles under the hood. If you are curious, read up on some of the more elaborate approaches such as HMMs in the context of NER in [1]."
},
{
"code": null,
"e": 3679,
"s": 3524,
"text": "Assuming the two entities are recognized correctly, we notice that the relational phrase still sits between them. That is, this sentence has the structure"
},
{
"code": null,
"e": 3721,
"s": 3679,
"text": "<words> book-title by person-name <words>"
},
{
"code": null,
"e": 3789,
"s": 3721,
"text": "Below is the POS analysis of the relevant portion of this sentence."
},
{
"code": null,
"e": 3924,
"s": 3789,
"text": "That the word by sandwiched between the entities is a preposition is assuring. It supports forming the relational phrase from this by."
},
{
"code": null,
"e": 4064,
"s": 3924,
"text": "Let’s use this opportunity to ‘dig’ into by a bit more. It's easy to imagine that in a huge corpus we may come across numerous instances of"
},
{
"code": null,
"e": 4090,
"s": 4064,
"text": "book-title by person-name"
},
{
"code": null,
"e": 4521,
"s": 4090,
"text": "From these instances, we will be able to also infer that the book title always precedes the by and that the person's name always follows it. Thus in principle, the word by can be used as an additional predictor of the entities themselves, in our case the book’s title and the person’s name. Consider replacing by with written by. The predictive strength of the latter towards the book title and person name entities is now higher."
},
{
"code": null,
"e": 4541,
"s": 4521,
"text": "Next, let’s look at"
},
{
"code": null,
"e": 4632,
"s": 4541,
"text": "Wimbledon is a tennis tournament held in the UK in the first two weeks of July every year."
},
{
"code": null,
"e": 4716,
"s": 4632,
"text": "This one could be ‘parsed’ via entity recognition (somewhat broadly interpreted) as"
},
{
"code": null,
"e": 4790,
"s": 4716,
"text": "Sports event name is a sport tournament held in the location in the time."
},
{
"code": null,
"e": 5238,
"s": 4790,
"text": "The first three entities are reasonably crisp and can be detected via NER approaches suitably trained. The fourth one, time, is less crisp. In our example, its value is first two weeks of July every year. It might be difficult to train a NER for this less crisp entity. Instead, we might consider recognizing more granular time-based entities. Such as month. Armed with such a detector we have a partial inference of in the time as in month: July."
},
{
"code": null,
"e": 5653,
"s": 5238,
"text": "Let’s now look at location. It makes sense to treat it in a hierarchical fashion. Specifically, to break location down into finer entities such as country, state, city, ... We can then recognize each of these entities and use a taxonomy to relate them. Such as country is-a location, state is-a location, state is-in country, etc.(Note that a particular state may be in multiple is-in associations with countries.)"
},
{
"code": null,
"e": 5784,
"s": 5653,
"text": "Okay, now that we have discussed the entities, what relationships can we infer among them? Definitely the is-a relationship below."
},
{
"code": null,
"e": 5824,
"s": 5784,
"text": "Sports event name is-a sport tournament"
},
{
"code": null,
"e": 5950,
"s": 5824,
"text": "The other ones need more thought. First, for convenience, let’s abbreviate the sentence with entity variables in it as below."
},
{
"code": null,
"e": 5986,
"s": 5950,
"text": "SEN is a ST held in the L in the T."
},
{
"code": null,
"e": 6123,
"s": 5986,
"text": "In our example, we see that ST held-in L would be a wrong inference. It is SEN=Wimbledon that is held in L=UK, not ST=tennis tournament?"
},
{
"code": null,
"e": 6235,
"s": 6123,
"text": "An idea worth exploring is to start by forming three hypotheses, expressed in the form of association rules [3]"
},
{
"code": null,
"e": 6352,
"s": 6235,
"text": "ST=tennis tournament, held-in ⇒ L=UKSEN=Wimbledon, held-in ⇒ L=UKSEN=Wimbledon, ST=tennis tournament, held-in ⇒ L=UK"
},
{
"code": null,
"e": 6384,
"s": 6352,
"text": "In the above, think of X ⇒ Y as"
},
{
"code": null,
"e": 6396,
"s": 6384,
"text": "IF X THEN Y"
},
{
"code": null,
"e": 6682,
"s": 6396,
"text": "Given a huge corpus, such as Wikipedia, broken down into individual sentences, we can then compute the so-called supports and confidences of each of these association rules. The support of a rule X ⇒ Y is the number of sentences in which X holds. The confidence of this rule is P(Y|X)."
},
{
"code": null,
"e": 6869,
"s": 6682,
"text": "From such an analysis we can reasonably expect to infer that ST=tennis tournament does not imply that it is held in the UK whereas SEN=Wimbledon always implies that it is held in the UK."
},
{
"code": null,
"e": 7137,
"s": 6869,
"text": "Next, consider the in relation involving T (time). We can treat it similarly. Our set of candidate association rules is a bit larger. In X ⇒ Y, Y is always T = first two weeks of July every year. X is any nonempty subset of {SEN=Wimbledon, ST=tennis tournament, L=UK}"
},
{
"code": null,
"e": 7511,
"s": 7137,
"text": "Framing this problem as one involving mining for high-confidence association rules lets us use highly scalable algorithms that have been developed for this problem. Such as FP growth or the A’priori algorithm. See [3]. We may indeed confront scale if we are going to do this analysis on all sentences in Wikipedia, many having more than two entities in them (as does ours)."
},
{
"code": null,
"e": 7572,
"s": 7511,
"text": "Finally, let’s turn our attention to the following sentence."
},
{
"code": null,
"e": 7703,
"s": 7572,
"text": "In 2019, the men’s singles winner was Novak Djokovic who defeated Roger Federer in the longest singles final in Wimbledon history."
},
{
"code": null,
"e": 8020,
"s": 7703,
"text": "This sentence is a good one to illustrate going beyond relating the entities that occur in the sentence from its contents alone. Rather, we will infer (or more accurately, collect evidence for) relationships that may be inferred from combining the information in this sentence with a suitable global knowledge model."
},
{
"code": null,
"e": 8211,
"s": 8020,
"text": "We won’t actually specify the knowledge model’s form. Rather we will muse on what we might be able to infer from the information in this sentence were we to also have access to such a model."
},
{
"code": null,
"e": 8216,
"s": 8211,
"text": "From"
},
{
"code": null,
"e": 8258,
"s": 8216,
"text": "Novak Djokovic who defeated Roger Federer"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "we can extract"
},
{
"code": null,
"e": 8339,
"s": 8273,
"text": "defeated(Person Name: Novak Dkokovic, Person Name: Roger Federer)"
},
{
"code": null,
"e": 8372,
"s": 8339,
"text": "in the manner discussed earlier."
},
{
"code": null,
"e": 8724,
"s": 8372,
"text": "Now consider the word Wimbledon that appears in the same sentence later on. Assume its been correctly recognized as Sports Event Name. We may now be able to link these person names to this event. If so, and assuming our knowledge graph knows that Wimbledon is a tennis event, we can also infer that Novak Dkokovic and Roger Federer are tennis players."
},
{
"code": null,
"e": 9009,
"s": 8724,
"text": "We are listing the inferences in the last sentence of the previous paragraph mainly to illustrate what sorts of things we can deduce. For these particular assertions — that these people are tennis players — there may be stronger, more direct, evidence in other sentences in Wikipedia."
}
]
|
How to add whatsapp share button on a website ? - GeeksforGeeks | 30 Jul, 2021
WhatsApp is the most popular messaging app. This article describes how you can add WhatsApp share button in your website.
Note: This will work only when website is open in mobile with WhatsApp installed.
Step 1: Design a simple webpage with a hyperlink on it. Sharing will be done when user click on this link.
HTML
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title> How to add WhatsApp share button on website? </title></head> <body> <h3>Whatsapp sharing</h3> <a>Share to whatsapp</a></body> </html>
Step 2: This will not work on desktop\laptop so let’s add CSS to hide it on large screens. To do so CSS @media query is used.
<style type="text/css">
@media screen and (min-width: 500px) {
a {
display: none
}
}
</style>
Example 1: This example is implemented using above two steps. Notice the href attribute specifies the location and this request is sent to WhatsApp application.
Syntax:
href="whatsapp://send?text=Your message here"
HTML
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to add WhatsApp share button on website? </title> <style type="text/css"> @media screen and (min-width: 500px) { a { display: none } } </style></head> <body> <h3>Whatsapp sharing</h3> <a href="whatsapp://send?text=GFG Example for whatsapp sharing" data-action="share/whatsapp/share" target="_blank"> Share to whatsapp </a></body> </html>
Save this file and open in mobile phone.
Output:
Example 2: In this example, we will take input from user and send that message using JavaScript. In this example, we have defined a class to show content only on mobile.
HTML
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to add whatsapp share button on website? </title> <style type="text/css"> /* To show on small size screen only */ @media screen and (min-width: 500px) { .mobileShow { display: none } } </style></head> <body> <h3>Whatsapp sharing</h3> <input class="mobileShow" type="text" name="message"> <button onclick="share()" class="mobileShow"> Share to whatsapp </button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"> </script> <script type="text/javascript"> // Function to share on whatsapp function share() { // Getting user input var message = $("input[name=message]").val(); // Opening URL window.open( "whatsapp://send?text=" + message, // This is what makes it // open in a new window. '_blank' ); } </script></body> </html>
Output:
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
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set div width to fit content using CSS ?
Making a div vertically scrollable using CSS
How to set fixed width for <td> in a table ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25152,
"s": 25124,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25274,
"s": 25152,
"text": "WhatsApp is the most popular messaging app. This article describes how you can add WhatsApp share button in your website."
},
{
"code": null,
"e": 25356,
"s": 25274,
"text": "Note: This will work only when website is open in mobile with WhatsApp installed."
},
{
"code": null,
"e": 25464,
"s": 25356,
"text": "Step 1: Design a simple webpage with a hyperlink on it. Sharing will be done when user click on this link."
},
{
"code": null,
"e": 25469,
"s": 25464,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> <title> How to add WhatsApp share button on website? </title></head> <body> <h3>Whatsapp sharing</h3> <a>Share to whatsapp</a></body> </html>",
"e": 25754,
"s": 25469,
"text": null
},
{
"code": null,
"e": 25880,
"s": 25754,
"text": "Step 2: This will not work on desktop\\laptop so let’s add CSS to hide it on large screens. To do so CSS @media query is used."
},
{
"code": null,
"e": 26011,
"s": 25880,
"text": "<style type=\"text/css\">\n @media screen and (min-width: 500px) {\n a {\n display: none\n }\n }\n</style>\n"
},
{
"code": null,
"e": 26172,
"s": 26011,
"text": "Example 1: This example is implemented using above two steps. Notice the href attribute specifies the location and this request is sent to WhatsApp application."
},
{
"code": null,
"e": 26180,
"s": 26172,
"text": "Syntax:"
},
{
"code": null,
"e": 26227,
"s": 26180,
"text": "href=\"whatsapp://send?text=Your message here\"\n"
},
{
"code": null,
"e": 26232,
"s": 26227,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to add WhatsApp share button on website? </title> <style type=\"text/css\"> @media screen and (min-width: 500px) { a { display: none } } </style></head> <body> <h3>Whatsapp sharing</h3> <a href=\"whatsapp://send?text=GFG Example for whatsapp sharing\" data-action=\"share/whatsapp/share\" target=\"_blank\"> Share to whatsapp </a></body> </html>",
"e": 26889,
"s": 26232,
"text": null
},
{
"code": null,
"e": 26930,
"s": 26889,
"text": "Save this file and open in mobile phone."
},
{
"code": null,
"e": 26938,
"s": 26930,
"text": "Output:"
},
{
"code": null,
"e": 27108,
"s": 26938,
"text": "Example 2: In this example, we will take input from user and send that message using JavaScript. In this example, we have defined a class to show content only on mobile."
},
{
"code": null,
"e": 27113,
"s": 27108,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to add whatsapp share button on website? </title> <style type=\"text/css\"> /* To show on small size screen only */ @media screen and (min-width: 500px) { .mobileShow { display: none } } </style></head> <body> <h3>Whatsapp sharing</h3> <input class=\"mobileShow\" type=\"text\" name=\"message\"> <button onclick=\"share()\" class=\"mobileShow\"> Share to whatsapp </button> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js\"> </script> <script type=\"text/javascript\"> // Function to share on whatsapp function share() { // Getting user input var message = $(\"input[name=message]\").val(); // Opening URL window.open( \"whatsapp://send?text=\" + message, // This is what makes it // open in a new window. '_blank' ); } </script></body> </html>",
"e": 28368,
"s": 27113,
"text": null
},
{
"code": null,
"e": 28376,
"s": 28368,
"text": "Output:"
},
{
"code": null,
"e": 28570,
"s": 28376,
"text": "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."
},
{
"code": null,
"e": 28756,
"s": 28570,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 28765,
"s": 28756,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28775,
"s": 28765,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28779,
"s": 28775,
"text": "CSS"
},
{
"code": null,
"e": 28784,
"s": 28779,
"text": "HTML"
},
{
"code": null,
"e": 28795,
"s": 28784,
"text": "JavaScript"
},
{
"code": null,
"e": 28812,
"s": 28795,
"text": "Web Technologies"
},
{
"code": null,
"e": 28839,
"s": 28812,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28844,
"s": 28839,
"text": "HTML"
},
{
"code": null,
"e": 28942,
"s": 28844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28979,
"s": 28942,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29020,
"s": 28979,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29068,
"s": 29020,
"text": "How to set div width to fit content using CSS ?"
},
{
"code": null,
"e": 29113,
"s": 29068,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 29158,
"s": 29113,
"text": "How to set fixed width for <td> in a table ?"
},
{
"code": null,
"e": 29218,
"s": 29158,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29279,
"s": 29218,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29332,
"s": 29279,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29382,
"s": 29332,
"text": "How to Insert Form Data into Database using PHP ?"
}
]
|
SQLAlchemy Core - Using Multiple Tables | One of the important features of RDBMS is establishing relation between tables. SQL operations like SELECT, UPDATE and DELETE can be performed on related tables. This section describes these operations using SQLAlchemy.
For this purpose, two tables are created in our SQLite database (college.db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint.
The following code will create two tables in college.db −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey
engine = create_engine('sqlite:///college.db', echo=True)
meta = MetaData()
students = Table(
'students', meta,
Column('id', Integer, primary_key = True),
Column('name', String),
Column('lastname', String),
)
addresses = Table(
'addresses', meta,
Column('id', Integer, primary_key = True),
Column('st_id', Integer, ForeignKey('students.id')),
Column('postal_add', String),
Column('email_add', String))
meta.create_all(engine)
Above code will translate to CREATE TABLE queries for students and addresses table as below −
CREATE TABLE students (
id INTEGER NOT NULL,
name VARCHAR,
lastname VARCHAR,
PRIMARY KEY (id)
)
CREATE TABLE addresses (
id INTEGER NOT NULL,
st_id INTEGER,
postal_add VARCHAR,
email_add VARCHAR,
PRIMARY KEY (id),
FOREIGN KEY(st_id) REFERENCES students (id)
)
The following screenshots present the above code very clearly −
These tables are populated with data by executing insert() method of table objects. To insert 5 rows in students table, you can use the code given below −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()
conn = engine.connect()
students = Table(
'students', meta,
Column('id', Integer, primary_key = True),
Column('name', String),
Column('lastname', String),
)
conn.execute(students.insert(), [
{'name':'Ravi', 'lastname':'Kapoor'},
{'name':'Rajiv', 'lastname' : 'Khanna'},
{'name':'Komal','lastname' : 'Bhandari'},
{'name':'Abdul','lastname' : 'Sattar'},
{'name':'Priya','lastname' : 'Rajhans'},
])
Rows are added in addresses table with the help of the following code −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()
conn = engine.connect()
addresses = Table(
'addresses', meta,
Column('id', Integer, primary_key = True),
Column('st_id', Integer),
Column('postal_add', String),
Column('email_add', String)
)
conn.execute(addresses.insert(), [
{'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'[email protected]'},
{'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'[email protected]'},
{'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'[email protected]'},
{'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'[email protected]'},
{'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'[email protected]'},
])
Note that the st_id column in addresses table refers to id column in students table. We can now use this relation to fetch data from both the tables. We want to fetch name and lastname from students table corresponding to st_id in the addresses table.
from sqlalchemy.sql import select
s = select([students, addresses]).where(students.c.id == addresses.c.st_id)
result = conn.execute(s)
for row in result:
print (row)
The select objects will effectively translate into following SQL expression joining two tables on common relation −
SELECT students.id,
students.name,
students.lastname,
addresses.id,
addresses.st_id,
addresses.postal_add,
addresses.email_add
FROM students, addresses
WHERE students.id = addresses.st_id
This will produce output extracting corresponding data from both tables as follows −
(1, 'Ravi', 'Kapoor', 1, 1, 'Shivajinagar Pune', '[email protected]')
(1, 'Ravi', 'Kapoor', 2, 1, 'ChurchGate Mumbai', '[email protected]')
(3, 'Komal', 'Bhandari', 3, 3, 'Jubilee Hills Hyderabad', '[email protected]')
(5, 'Priya', 'Rajhans', 4, 5, 'MG Road Bangaluru', '[email protected]')
(2, 'Rajiv', 'Khanna', 5, 2, 'Cannought Place new Delhi', '[email protected]')
21 Lectures
1.5 hours
Jack Chan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2560,
"s": 2340,
"text": "One of the important features of RDBMS is establishing relation between tables. SQL operations like SELECT, UPDATE and DELETE can be performed on related tables. This section describes these operations using SQLAlchemy."
},
{
"code": null,
"e": 2836,
"s": 2560,
"text": "For this purpose, two tables are created in our SQLite database (college.db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint."
},
{
"code": null,
"e": 2894,
"s": 2836,
"text": "The following code will create two tables in college.db −"
},
{
"code": null,
"e": 3449,
"s": 2894,
"text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey\nengine = create_engine('sqlite:///college.db', echo=True)\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer, ForeignKey('students.id')), \n Column('postal_add', String), \n Column('email_add', String))\n\nmeta.create_all(engine)"
},
{
"code": null,
"e": 3543,
"s": 3449,
"text": "Above code will translate to CREATE TABLE queries for students and addresses table as below −"
},
{
"code": null,
"e": 3834,
"s": 3543,
"text": "CREATE TABLE students (\n id INTEGER NOT NULL,\n name VARCHAR,\n lastname VARCHAR,\n PRIMARY KEY (id)\n)\n\nCREATE TABLE addresses (\n id INTEGER NOT NULL,\n st_id INTEGER,\n postal_add VARCHAR,\n email_add VARCHAR,\n PRIMARY KEY (id),\n FOREIGN KEY(st_id) REFERENCES students (id)\n)"
},
{
"code": null,
"e": 3898,
"s": 3834,
"text": "The following screenshots present the above code very clearly −"
},
{
"code": null,
"e": 4053,
"s": 3898,
"text": "These tables are populated with data by executing insert() method of table objects. To insert 5 rows in students table, you can use the code given below −"
},
{
"code": null,
"e": 4639,
"s": 4053,
"text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\n\nconn = engine.connect()\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nconn.execute(students.insert(), [\n {'name':'Ravi', 'lastname':'Kapoor'},\n {'name':'Rajiv', 'lastname' : 'Khanna'},\n {'name':'Komal','lastname' : 'Bhandari'},\n {'name':'Abdul','lastname' : 'Sattar'},\n {'name':'Priya','lastname' : 'Rajhans'},\n])"
},
{
"code": null,
"e": 4711,
"s": 4639,
"text": "Rows are added in addresses table with the help of the following code −"
},
{
"code": null,
"e": 5535,
"s": 4711,
"text": "from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\nmeta = MetaData()\nconn = engine.connect()\n\naddresses = Table(\n 'addresses', meta, \n Column('id', Integer, primary_key = True), \n Column('st_id', Integer), \n Column('postal_add', String), \n Column('email_add', String)\n)\n\nconn.execute(addresses.insert(), [\n {'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'[email protected]'},\n {'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'[email protected]'},\n {'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'[email protected]'},\n {'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'[email protected]'},\n {'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'[email protected]'},\n])"
},
{
"code": null,
"e": 5787,
"s": 5535,
"text": "Note that the st_id column in addresses table refers to id column in students table. We can now use this relation to fetch data from both the tables. We want to fetch name and lastname from students table corresponding to st_id in the addresses table."
},
{
"code": null,
"e": 5957,
"s": 5787,
"text": "from sqlalchemy.sql import select\ns = select([students, addresses]).where(students.c.id == addresses.c.st_id)\nresult = conn.execute(s)\n\nfor row in result:\n print (row)"
},
{
"code": null,
"e": 6073,
"s": 5957,
"text": "The select objects will effectively translate into following SQL expression joining two tables on common relation −"
},
{
"code": null,
"e": 6285,
"s": 6073,
"text": "SELECT students.id, \n students.name, \n students.lastname, \n addresses.id, \n addresses.st_id, \n addresses.postal_add, \n addresses.email_add\nFROM students, addresses\nWHERE students.id = addresses.st_id"
},
{
"code": null,
"e": 6370,
"s": 6285,
"text": "This will produce output extracting corresponding data from both tables as follows −"
},
{
"code": null,
"e": 6729,
"s": 6370,
"text": "(1, 'Ravi', 'Kapoor', 1, 1, 'Shivajinagar Pune', '[email protected]')\n(1, 'Ravi', 'Kapoor', 2, 1, 'ChurchGate Mumbai', '[email protected]')\n(3, 'Komal', 'Bhandari', 3, 3, 'Jubilee Hills Hyderabad', '[email protected]')\n(5, 'Priya', 'Rajhans', 4, 5, 'MG Road Bangaluru', '[email protected]')\n(2, 'Rajiv', 'Khanna', 5, 2, 'Cannought Place new Delhi', '[email protected]')\n"
},
{
"code": null,
"e": 6764,
"s": 6729,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6775,
"s": 6764,
"text": " Jack Chan"
},
{
"code": null,
"e": 6782,
"s": 6775,
"text": " Print"
},
{
"code": null,
"e": 6793,
"s": 6782,
"text": " Add Notes"
}
]
|
Python 3 - Tkinter place() Method | This geometry manager organizes widgets by placing them in a specific position in the parent widget.
widget.place( place_options )
Here is the list of possible options −
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
height, width − Height and width in pixels.
height, width − Height and width in pixels.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
x, y − Horizontal and vertical offset in pixels.
x, y − Horizontal and vertical offset in pixels.
Try the following example by moving cursor on different buttons −
# !/usr/bin/python3
from tkinter import *
top = Tk()
L1 = Label(top, text = "Physics")
L1.place(x = 10,y = 10)
E1 = Entry(top, bd = 5)
E1.place(x = 60,y = 10)
L2 = Label(top,text = "Maths")
L2.place(x = 10,y = 50)
E2 = Entry(top,bd = 5)
E2.place(x = 60,y = 50)
L3 = Label(top,text = "Total")
L3.place(x = 10,y = 150)
E3 = Entry(top,bd = 5)
E3.place(x = 60,y = 150)
B = Button(top, text = "Add")
B.place(x = 100, y = 100)
top.geometry("250x250+10+10")
top.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2441,
"s": 2340,
"text": "This geometry manager organizes widgets by placing them in a specific position in the parent widget."
},
{
"code": null,
"e": 2472,
"s": 2441,
"text": "widget.place( place_options )\n"
},
{
"code": null,
"e": 2511,
"s": 2472,
"text": "Here is the list of possible options −"
},
{
"code": null,
"e": 2718,
"s": 2511,
"text": "anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)"
},
{
"code": null,
"e": 2925,
"s": 2718,
"text": "anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)"
},
{
"code": null,
"e": 3070,
"s": 2925,
"text": "bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise."
},
{
"code": null,
"e": 3215,
"s": 3070,
"text": "bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise."
},
{
"code": null,
"e": 3259,
"s": 3215,
"text": "height, width − Height and width in pixels."
},
{
"code": null,
"e": 3303,
"s": 3259,
"text": "height, width − Height and width in pixels."
},
{
"code": null,
"e": 3434,
"s": 3303,
"text": "relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3565,
"s": 3434,
"text": "relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3701,
"s": 3565,
"text": "relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3837,
"s": 3701,
"text": "relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget."
},
{
"code": null,
"e": 3886,
"s": 3837,
"text": "x, y − Horizontal and vertical offset in pixels."
},
{
"code": null,
"e": 3935,
"s": 3886,
"text": "x, y − Horizontal and vertical offset in pixels."
},
{
"code": null,
"e": 4001,
"s": 3935,
"text": "Try the following example by moving cursor on different buttons −"
},
{
"code": null,
"e": 4470,
"s": 4001,
"text": "# !/usr/bin/python3\nfrom tkinter import *\n\ntop = Tk()\nL1 = Label(top, text = \"Physics\")\nL1.place(x = 10,y = 10)\nE1 = Entry(top, bd = 5)\nE1.place(x = 60,y = 10)\nL2 = Label(top,text = \"Maths\")\nL2.place(x = 10,y = 50)\nE2 = Entry(top,bd = 5)\nE2.place(x = 60,y = 50)\n\nL3 = Label(top,text = \"Total\")\nL3.place(x = 10,y = 150)\nE3 = Entry(top,bd = 5)\nE3.place(x = 60,y = 150)\n\nB = Button(top, text = \"Add\")\nB.place(x = 100, y = 100)\ntop.geometry(\"250x250+10+10\")\ntop.mainloop()"
},
{
"code": null,
"e": 4538,
"s": 4470,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4575,
"s": 4538,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4591,
"s": 4575,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4624,
"s": 4591,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4643,
"s": 4624,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4678,
"s": 4643,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4700,
"s": 4678,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4734,
"s": 4700,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4762,
"s": 4734,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4797,
"s": 4762,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4811,
"s": 4797,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4844,
"s": 4811,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4861,
"s": 4844,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4868,
"s": 4861,
"text": " Print"
},
{
"code": null,
"e": 4879,
"s": 4868,
"text": " Add Notes"
}
]
|
ES6 - Array Method join() | join() method joins all the elements of an array into a string.
array.join(separator);
separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.
separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.
Returns a string after joining all the array elements.
var arr = new Array("First","Second","Third");
var str = arr.join();console.log("str : " + str );
var str = arr.join(", ");
console.log("str : " + str );
var str = arr.join(" + ");
console.log("str : " + str );
str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2341,
"s": 2277,
"text": "join() method joins all the elements of an array into a string."
},
{
"code": null,
"e": 2368,
"s": 2341,
"text": "array.join(separator); \n"
},
{
"code": null,
"e": 2497,
"s": 2368,
"text": "separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma."
},
{
"code": null,
"e": 2626,
"s": 2497,
"text": "separator − Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma."
},
{
"code": null,
"e": 2681,
"s": 2626,
"text": "Returns a string after joining all the array elements."
},
{
"code": null,
"e": 2902,
"s": 2681,
"text": "var arr = new Array(\"First\",\"Second\",\"Third\"); \nvar str = arr.join();console.log(\"str : \" + str ); \nvar str = arr.join(\", \"); \nconsole.log(\"str : \" + str ); \n\nvar str = arr.join(\" + \"); \nconsole.log(\"str : \" + str ); "
},
{
"code": null,
"e": 2987,
"s": 2902,
"text": "str : First,Second,Third \nstr : First, Second, Third \nstr : First + Second + Third \n"
},
{
"code": null,
"e": 3022,
"s": 2987,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3036,
"s": 3022,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 3069,
"s": 3036,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3087,
"s": 3069,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3120,
"s": 3087,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3134,
"s": 3120,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3169,
"s": 3134,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3186,
"s": 3169,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3219,
"s": 3186,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3235,
"s": 3219,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3270,
"s": 3235,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3278,
"s": 3270,
"text": " Shweta"
},
{
"code": null,
"e": 3285,
"s": 3278,
"text": " Print"
},
{
"code": null,
"e": 3296,
"s": 3285,
"text": " Add Notes"
}
]
|
Which packages contain Wrapper class in Java? | Java provides certain classes called wrapper classes in the java.lang package. The objects of these classes wrap primitive datatypes within them. Following is the list of primitive data types and their respective classes −
Wrapper classes in Java belong to the java.lang package, Therefore there is no need to import any package explicitly while working with them.
The following Java example accepts various primitive variables from the user and creates their respective wrapper classes.
Live Demo
import java.util.Scanner;
public class WrapperClassesExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
//Wrapper class of an integer
Integer obj1 = new Integer(i);
System.out.println("Enter a long value: ");
long l = sc.nextLong();
//Wrapper class of a long
Long obj2 = new Long(l);
System.out.println("Enter a float value: ");
float f = sc.nextFloat();
//Wrapper class of a float
Float obj3 = new Float(f);
System.out.println("Enter a double value: ");
double d = sc.nextDouble();
//Wrapper class of a double
Double obj4 = new Double(d);
System.out.println("Enter a boolean value: ");
boolean bool = sc.nextBoolean();
//Wrapper class of a boolean
Boolean obj5 = new Boolean(bool);
System.out.println("Enter a char value: ");
char ch = sc.next().toCharArray()[0];
//Wrapper class of a boolean
Character obj6 = new Character(ch);
System.out.println("Enter a byte value: ");
byte by = sc.nextByte();
//Wrapper class of a boolean
Byte obj7 = new Byte(by);
System.out.println("Enter a short value: ");
short sh = sc.nextShort();
//Wrapper class of a boolean
Short obj8 = new Short(sh);
}
}
Enter an integer value:
254
Enter a long value:
4444445455454
Enter a float value:
12.324
Enter a double value:
1236.22325
Enter a boolean value:
true
Enter a char value:
c
Enter a byte value:
125
Enter a short value:
14233 | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "Java provides certain classes called wrapper classes in the java.lang package. The objects of these classes wrap primitive datatypes within them. Following is the list of primitive data types and their respective classes −"
},
{
"code": null,
"e": 1427,
"s": 1285,
"text": "Wrapper classes in Java belong to the java.lang package, Therefore there is no need to import any package explicitly while working with them."
},
{
"code": null,
"e": 1550,
"s": 1427,
"text": "The following Java example accepts various primitive variables from the user and creates their respective wrapper classes."
},
{
"code": null,
"e": 1561,
"s": 1550,
"text": " Live Demo"
},
{
"code": null,
"e": 2958,
"s": 1561,
"text": "import java.util.Scanner;\npublic class WrapperClassesExample {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter an integer value: \");\n int i = sc.nextInt();\n //Wrapper class of an integer\n Integer obj1 = new Integer(i);\n System.out.println(\"Enter a long value: \");\n long l = sc.nextLong();\n //Wrapper class of a long\n Long obj2 = new Long(l);\n System.out.println(\"Enter a float value: \");\n float f = sc.nextFloat();\n //Wrapper class of a float\n Float obj3 = new Float(f);\n System.out.println(\"Enter a double value: \");\n double d = sc.nextDouble();\n //Wrapper class of a double\n Double obj4 = new Double(d);\n System.out.println(\"Enter a boolean value: \");\n boolean bool = sc.nextBoolean();\n //Wrapper class of a boolean\n Boolean obj5 = new Boolean(bool);\n System.out.println(\"Enter a char value: \");\n char ch = sc.next().toCharArray()[0];\n //Wrapper class of a boolean\n Character obj6 = new Character(ch);\n System.out.println(\"Enter a byte value: \");\n byte by = sc.nextByte();\n //Wrapper class of a boolean\n Byte obj7 = new Byte(by);\n System.out.println(\"Enter a short value: \");\n short sh = sc.nextShort();\n //Wrapper class of a boolean\n Short obj8 = new Short(sh);\n }\n}"
},
{
"code": null,
"e": 3182,
"s": 2958,
"text": "Enter an integer value:\n254\nEnter a long value:\n4444445455454\nEnter a float value:\n12.324\nEnter a double value:\n1236.22325\nEnter a boolean value:\ntrue\nEnter a char value:\nc\nEnter a byte value:\n125\nEnter a short value:\n14233"
}
]
|
Python dictionary items() Method | Python dictionary method items() returns a list of dict's (key, value) tuple pairs
Following is the syntax for items() method −
dict.items()
NA
NA
This method returns a list of tuple pairs.
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.items()
When we run above program, it produces following result −
Value : [('Age', 7), ('Name', 'Zara')]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2328,
"s": 2244,
"text": "Python dictionary method items() returns a list of dict's (key, value) tuple pairs"
},
{
"code": null,
"e": 2373,
"s": 2328,
"text": "Following is the syntax for items() method −"
},
{
"code": null,
"e": 2387,
"s": 2373,
"text": "dict.items()\n"
},
{
"code": null,
"e": 2390,
"s": 2387,
"text": "NA"
},
{
"code": null,
"e": 2393,
"s": 2390,
"text": "NA"
},
{
"code": null,
"e": 2436,
"s": 2393,
"text": "This method returns a list of tuple pairs."
},
{
"code": null,
"e": 2493,
"s": 2436,
"text": "The following example shows the usage of items() method."
},
{
"code": null,
"e": 2581,
"s": 2493,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7}\nprint \"Value : %s\" % dict.items()"
},
{
"code": null,
"e": 2639,
"s": 2581,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2679,
"s": 2639,
"text": "Value : [('Age', 7), ('Name', 'Zara')]\n"
},
{
"code": null,
"e": 2716,
"s": 2679,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2732,
"s": 2716,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2765,
"s": 2732,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2784,
"s": 2765,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2819,
"s": 2784,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2841,
"s": 2819,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 2875,
"s": 2841,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 2903,
"s": 2875,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 2938,
"s": 2903,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 2952,
"s": 2938,
"text": " Lets Kode It"
},
{
"code": null,
"e": 2985,
"s": 2952,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3002,
"s": 2985,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3009,
"s": 3002,
"text": " Print"
},
{
"code": null,
"e": 3020,
"s": 3009,
"text": " Add Notes"
}
]
|
Automate python scripts with AWS Lightsail | by Eric Landstein | Towards Data Science | In my work as a data scientist, I have come to realize how necessary it is to automate any and every aspect of the workflow. When most people hear the words data science, they often think machine learning and AI, but really most of a data scientist’s time is spent on various kinds of work. In this blog I will be focusing on the data collection automation using AWS Lightsail.
The project outlined below is all hosted on my github
1. Create a AWS Lightsail Ubuntu instance
2. Apply a dedicated IP address to the instance
3. Install Python3.7 and PIP on the Ubuntu instance
4. Clone python repository to the instance
The python script will call reddit’s api and store all submissions from reddit.com/r/learnpython into a csv
5. Create a cron job that will run every hour
Create an Ubuntu LightSail Instance on Amazon Web Services
If you’re an individual developer or hobbyist working on a personal project, Lightsail can help you deploy and manage basic cloud resources. Amazon Lightsail is the easiest way to get started with AWS if you just need virtual private servers. Lightsail includes everything you need to launch your project quickly — a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP. After you create your instance, you can easily connect to it. You can manage your instances using the Lightsail console, Lightsail API, or Lightsail command line interface (CLI). (https://lightsail.aws.amazon.com/)
To begin you will need to sign up at Amazon LightSail. The first month is free which will give you plenty of time to decide if this service is what you need.
Once you have logged in, you should see the Lightsail dashboard.
Create an Ubuntu Instance
1. Click on the Create instance button (circled above).
2. Under pick your instance image, select Linux/Unix
3. Select OS only
4. Select Ubuntu 18.04
5. Choose your instance Plan: For this project I will be using the cheapest option ($3.50) as it is more than sufficient to run most python scripts. Also, don’t forget the first month is free!
6. Name your instance: For this project I named the instance “Ubuntu-Automation”
7. Select Create Instance
After selecting Create Instance you will be returned to the AWS LightSail dashboard. It will take the Ubuntu instance a few minutes to be created. While the instance is being created, the status will be “Pending” like in the screenshot below:
The status will change to “Running” once the instance has been created. You will also see the IP address assigned to the instance, for my instance the IP address is 3.227.241.208. This IP address is dynamic and will change every time you reboot the instance. Depending on the project you plan on hosting it may be necessary to set a Static IP address.
Create a Static IP Address
Creating a static IP is optional and only necessary if your project requires it. I will be creating a static IP address because I open my SQL server only to this IP address for security reasons. After the initial setup I prefer to SSH into the Ubuntu instance from my local machine and having a static IP makes this process easier.
1. Select the Networking tab in your Lightsail dashboard
2.Click on “Create static IP”
3. Select your Ubuntu Instance server under “Attach to an instance”
4. Give the Static IP a name
5. Click “Create”
You should then see your new static IP Address. This IP address will not change.
Moving forward, my static IP address will be 18.213.119.58 which is what i’ll be using for the remainder of this project.
Python Automation
For this project, I will be creating a python script that calls the Reddit API and collects all of the new submissions from reddit.com/r/learnpython. For the scope of this article, I will not be reviewing how this particular script works, however, you can view all of the code at GitHubLink.
Connecting to Ubuntu instance using SSH
From the Lightsail dashboard you can connect to your Ubuntu instance using the web based SSH tool. After the initial setup I prefer to use SSH as it is simpler, but I did find using the web based tool easier to interface with in regards to the setup reviewed in this blog.
Terminal SSH Connection
In the upper right-hand corner select Account > Account. This will bring you to the account dashboard where you can download your SSH Key.
Once in the Lightsail account dashboard select “SSH keys” and then Download.
On your local computer navigate to ~/.ssh by running the command cd ~/.ssh
cd ~/.ssh
Copy the downloaded key to this location
To check that the key has been copied to this location run the command ls to list all files. (Note this method will only work for Unix based operating systems.)
ls
To connect via SSH run the following command
ssh -i ~/.ssh/lightsail.pem -T ubuntu@{your_lightsail_IP_address}
My Ubuntu server’s IP address is 18.213.119.58. To connect I will use the following commands
The first time connecting you will see the following message:
Select Yes to connect to your Ubuntu Instance.
Once connected you will see the following:
Both the web based SSH connection and local terminal SSH connection are valid and work. I just prefer connecting via terminal.
Getting your python script on the Ubuntu Instance
My preferred method of downloading my python script onto the Ubuntu instance is via Git.
git clone https://github.com/Landstein/AWS-Lightsail.git
(If there are config files you need on your ubuntu instance that you don’t want hosted on github you can use Amazon’s S3 to transfer)
Installing Python3.7 and PIP
For installing Python and PIP I would recommend using the web based SSH through the Lightsail dashboard.
Once in the repository folder run the following command which will run the below code and install Python3.7 and PIP.
bash install_python.sh
Installing Python Libraries
Next install the python libraries praw and pandas. Run the batch file python_libraries.sh.
Praw: Python reddit aPI wrapper
Pandas: Data manipulation and analysis
bash python_libraries.sh
Setting a Cron Job
The software utility cron is a time-based job scheduler in unix-like computer operating systems. Users that set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration — though its general-purpose nature makes it useful for things like downloading files from the internet and downloading email at regular intervals (wikipeida.com).
In order to fully automate this process, the last step is to have a cron job run at a regular interval.
For this project I am going to have my script run every hour on the 15th minute. The cron command will look like this:
15 * * * * /usr/bin/python3 /home/ubuntu/AWS-Lightsail/learnpython_to_csv.py >> ~/cron.log 2>&1
If you would like to play around with setting different intervals for your cron job I recommend first taking a look at https://crontab.guru/ .
Creating a Cron Job
Set the editor to vim using the following command
export EDIOTR=vim
Enter vim and edit the cron jobs
crontab -e
At this point VIM will launch and you will be able to edit your cron jobs.
Press i to enter insert modeOnce in insert mode copy and paste the cron job into the editorPress EscapePress : (colon), w (write), q (quit) to save and exit from vim
Press i to enter insert mode
Once in insert mode copy and paste the cron job into the editor
Press Escape
Press : (colon), w (write), q (quit) to save and exit from vim
:wq
You are now finished and your script will run at the interval given in the cron job.
To check your cron jobs you can run the command crontab -l to see all current cron jobs.
crontab -l
For logging purposes, print statements and errors will be stored in the file cron.log. From the home directory run the following command.
cat cron.log
If you see similar output that means everything is working! | [
{
"code": null,
"e": 550,
"s": 172,
"text": "In my work as a data scientist, I have come to realize how necessary it is to automate any and every aspect of the workflow. When most people hear the words data science, they often think machine learning and AI, but really most of a data scientist’s time is spent on various kinds of work. In this blog I will be focusing on the data collection automation using AWS Lightsail."
},
{
"code": null,
"e": 604,
"s": 550,
"text": "The project outlined below is all hosted on my github"
},
{
"code": null,
"e": 646,
"s": 604,
"text": "1. Create a AWS Lightsail Ubuntu instance"
},
{
"code": null,
"e": 694,
"s": 646,
"text": "2. Apply a dedicated IP address to the instance"
},
{
"code": null,
"e": 746,
"s": 694,
"text": "3. Install Python3.7 and PIP on the Ubuntu instance"
},
{
"code": null,
"e": 789,
"s": 746,
"text": "4. Clone python repository to the instance"
},
{
"code": null,
"e": 897,
"s": 789,
"text": "The python script will call reddit’s api and store all submissions from reddit.com/r/learnpython into a csv"
},
{
"code": null,
"e": 943,
"s": 897,
"text": "5. Create a cron job that will run every hour"
},
{
"code": null,
"e": 1002,
"s": 943,
"text": "Create an Ubuntu LightSail Instance on Amazon Web Services"
},
{
"code": null,
"e": 1618,
"s": 1002,
"text": "If you’re an individual developer or hobbyist working on a personal project, Lightsail can help you deploy and manage basic cloud resources. Amazon Lightsail is the easiest way to get started with AWS if you just need virtual private servers. Lightsail includes everything you need to launch your project quickly — a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP. After you create your instance, you can easily connect to it. You can manage your instances using the Lightsail console, Lightsail API, or Lightsail command line interface (CLI). (https://lightsail.aws.amazon.com/)"
},
{
"code": null,
"e": 1776,
"s": 1618,
"text": "To begin you will need to sign up at Amazon LightSail. The first month is free which will give you plenty of time to decide if this service is what you need."
},
{
"code": null,
"e": 1841,
"s": 1776,
"text": "Once you have logged in, you should see the Lightsail dashboard."
},
{
"code": null,
"e": 1867,
"s": 1841,
"text": "Create an Ubuntu Instance"
},
{
"code": null,
"e": 1923,
"s": 1867,
"text": "1. Click on the Create instance button (circled above)."
},
{
"code": null,
"e": 1976,
"s": 1923,
"text": "2. Under pick your instance image, select Linux/Unix"
},
{
"code": null,
"e": 1994,
"s": 1976,
"text": "3. Select OS only"
},
{
"code": null,
"e": 2017,
"s": 1994,
"text": "4. Select Ubuntu 18.04"
},
{
"code": null,
"e": 2210,
"s": 2017,
"text": "5. Choose your instance Plan: For this project I will be using the cheapest option ($3.50) as it is more than sufficient to run most python scripts. Also, don’t forget the first month is free!"
},
{
"code": null,
"e": 2291,
"s": 2210,
"text": "6. Name your instance: For this project I named the instance “Ubuntu-Automation”"
},
{
"code": null,
"e": 2317,
"s": 2291,
"text": "7. Select Create Instance"
},
{
"code": null,
"e": 2560,
"s": 2317,
"text": "After selecting Create Instance you will be returned to the AWS LightSail dashboard. It will take the Ubuntu instance a few minutes to be created. While the instance is being created, the status will be “Pending” like in the screenshot below:"
},
{
"code": null,
"e": 2912,
"s": 2560,
"text": "The status will change to “Running” once the instance has been created. You will also see the IP address assigned to the instance, for my instance the IP address is 3.227.241.208. This IP address is dynamic and will change every time you reboot the instance. Depending on the project you plan on hosting it may be necessary to set a Static IP address."
},
{
"code": null,
"e": 2939,
"s": 2912,
"text": "Create a Static IP Address"
},
{
"code": null,
"e": 3271,
"s": 2939,
"text": "Creating a static IP is optional and only necessary if your project requires it. I will be creating a static IP address because I open my SQL server only to this IP address for security reasons. After the initial setup I prefer to SSH into the Ubuntu instance from my local machine and having a static IP makes this process easier."
},
{
"code": null,
"e": 3328,
"s": 3271,
"text": "1. Select the Networking tab in your Lightsail dashboard"
},
{
"code": null,
"e": 3358,
"s": 3328,
"text": "2.Click on “Create static IP”"
},
{
"code": null,
"e": 3426,
"s": 3358,
"text": "3. Select your Ubuntu Instance server under “Attach to an instance”"
},
{
"code": null,
"e": 3455,
"s": 3426,
"text": "4. Give the Static IP a name"
},
{
"code": null,
"e": 3473,
"s": 3455,
"text": "5. Click “Create”"
},
{
"code": null,
"e": 3554,
"s": 3473,
"text": "You should then see your new static IP Address. This IP address will not change."
},
{
"code": null,
"e": 3676,
"s": 3554,
"text": "Moving forward, my static IP address will be 18.213.119.58 which is what i’ll be using for the remainder of this project."
},
{
"code": null,
"e": 3694,
"s": 3676,
"text": "Python Automation"
},
{
"code": null,
"e": 3986,
"s": 3694,
"text": "For this project, I will be creating a python script that calls the Reddit API and collects all of the new submissions from reddit.com/r/learnpython. For the scope of this article, I will not be reviewing how this particular script works, however, you can view all of the code at GitHubLink."
},
{
"code": null,
"e": 4026,
"s": 3986,
"text": "Connecting to Ubuntu instance using SSH"
},
{
"code": null,
"e": 4299,
"s": 4026,
"text": "From the Lightsail dashboard you can connect to your Ubuntu instance using the web based SSH tool. After the initial setup I prefer to use SSH as it is simpler, but I did find using the web based tool easier to interface with in regards to the setup reviewed in this blog."
},
{
"code": null,
"e": 4323,
"s": 4299,
"text": "Terminal SSH Connection"
},
{
"code": null,
"e": 4462,
"s": 4323,
"text": "In the upper right-hand corner select Account > Account. This will bring you to the account dashboard where you can download your SSH Key."
},
{
"code": null,
"e": 4539,
"s": 4462,
"text": "Once in the Lightsail account dashboard select “SSH keys” and then Download."
},
{
"code": null,
"e": 4614,
"s": 4539,
"text": "On your local computer navigate to ~/.ssh by running the command cd ~/.ssh"
},
{
"code": null,
"e": 4624,
"s": 4614,
"text": "cd ~/.ssh"
},
{
"code": null,
"e": 4665,
"s": 4624,
"text": "Copy the downloaded key to this location"
},
{
"code": null,
"e": 4826,
"s": 4665,
"text": "To check that the key has been copied to this location run the command ls to list all files. (Note this method will only work for Unix based operating systems.)"
},
{
"code": null,
"e": 4830,
"s": 4826,
"text": " ls"
},
{
"code": null,
"e": 4875,
"s": 4830,
"text": "To connect via SSH run the following command"
},
{
"code": null,
"e": 4941,
"s": 4875,
"text": "ssh -i ~/.ssh/lightsail.pem -T ubuntu@{your_lightsail_IP_address}"
},
{
"code": null,
"e": 5034,
"s": 4941,
"text": "My Ubuntu server’s IP address is 18.213.119.58. To connect I will use the following commands"
},
{
"code": null,
"e": 5096,
"s": 5034,
"text": "The first time connecting you will see the following message:"
},
{
"code": null,
"e": 5143,
"s": 5096,
"text": "Select Yes to connect to your Ubuntu Instance."
},
{
"code": null,
"e": 5186,
"s": 5143,
"text": "Once connected you will see the following:"
},
{
"code": null,
"e": 5313,
"s": 5186,
"text": "Both the web based SSH connection and local terminal SSH connection are valid and work. I just prefer connecting via terminal."
},
{
"code": null,
"e": 5363,
"s": 5313,
"text": "Getting your python script on the Ubuntu Instance"
},
{
"code": null,
"e": 5452,
"s": 5363,
"text": "My preferred method of downloading my python script onto the Ubuntu instance is via Git."
},
{
"code": null,
"e": 5509,
"s": 5452,
"text": "git clone https://github.com/Landstein/AWS-Lightsail.git"
},
{
"code": null,
"e": 5643,
"s": 5509,
"text": "(If there are config files you need on your ubuntu instance that you don’t want hosted on github you can use Amazon’s S3 to transfer)"
},
{
"code": null,
"e": 5672,
"s": 5643,
"text": "Installing Python3.7 and PIP"
},
{
"code": null,
"e": 5777,
"s": 5672,
"text": "For installing Python and PIP I would recommend using the web based SSH through the Lightsail dashboard."
},
{
"code": null,
"e": 5894,
"s": 5777,
"text": "Once in the repository folder run the following command which will run the below code and install Python3.7 and PIP."
},
{
"code": null,
"e": 5917,
"s": 5894,
"text": "bash install_python.sh"
},
{
"code": null,
"e": 5945,
"s": 5917,
"text": "Installing Python Libraries"
},
{
"code": null,
"e": 6036,
"s": 5945,
"text": "Next install the python libraries praw and pandas. Run the batch file python_libraries.sh."
},
{
"code": null,
"e": 6068,
"s": 6036,
"text": "Praw: Python reddit aPI wrapper"
},
{
"code": null,
"e": 6107,
"s": 6068,
"text": "Pandas: Data manipulation and analysis"
},
{
"code": null,
"e": 6132,
"s": 6107,
"text": "bash python_libraries.sh"
},
{
"code": null,
"e": 6151,
"s": 6132,
"text": "Setting a Cron Job"
},
{
"code": null,
"e": 6636,
"s": 6151,
"text": "The software utility cron is a time-based job scheduler in unix-like computer operating systems. Users that set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration — though its general-purpose nature makes it useful for things like downloading files from the internet and downloading email at regular intervals (wikipeida.com)."
},
{
"code": null,
"e": 6740,
"s": 6636,
"text": "In order to fully automate this process, the last step is to have a cron job run at a regular interval."
},
{
"code": null,
"e": 6859,
"s": 6740,
"text": "For this project I am going to have my script run every hour on the 15th minute. The cron command will look like this:"
},
{
"code": null,
"e": 6955,
"s": 6859,
"text": "15 * * * * /usr/bin/python3 /home/ubuntu/AWS-Lightsail/learnpython_to_csv.py >> ~/cron.log 2>&1"
},
{
"code": null,
"e": 7098,
"s": 6955,
"text": "If you would like to play around with setting different intervals for your cron job I recommend first taking a look at https://crontab.guru/ ."
},
{
"code": null,
"e": 7118,
"s": 7098,
"text": "Creating a Cron Job"
},
{
"code": null,
"e": 7168,
"s": 7118,
"text": "Set the editor to vim using the following command"
},
{
"code": null,
"e": 7186,
"s": 7168,
"text": "export EDIOTR=vim"
},
{
"code": null,
"e": 7219,
"s": 7186,
"text": "Enter vim and edit the cron jobs"
},
{
"code": null,
"e": 7230,
"s": 7219,
"text": "crontab -e"
},
{
"code": null,
"e": 7305,
"s": 7230,
"text": "At this point VIM will launch and you will be able to edit your cron jobs."
},
{
"code": null,
"e": 7471,
"s": 7305,
"text": "Press i to enter insert modeOnce in insert mode copy and paste the cron job into the editorPress EscapePress : (colon), w (write), q (quit) to save and exit from vim"
},
{
"code": null,
"e": 7500,
"s": 7471,
"text": "Press i to enter insert mode"
},
{
"code": null,
"e": 7564,
"s": 7500,
"text": "Once in insert mode copy and paste the cron job into the editor"
},
{
"code": null,
"e": 7577,
"s": 7564,
"text": "Press Escape"
},
{
"code": null,
"e": 7640,
"s": 7577,
"text": "Press : (colon), w (write), q (quit) to save and exit from vim"
},
{
"code": null,
"e": 7644,
"s": 7640,
"text": ":wq"
},
{
"code": null,
"e": 7729,
"s": 7644,
"text": "You are now finished and your script will run at the interval given in the cron job."
},
{
"code": null,
"e": 7818,
"s": 7729,
"text": "To check your cron jobs you can run the command crontab -l to see all current cron jobs."
},
{
"code": null,
"e": 7829,
"s": 7818,
"text": "crontab -l"
},
{
"code": null,
"e": 7967,
"s": 7829,
"text": "For logging purposes, print statements and errors will be stored in the file cron.log. From the home directory run the following command."
},
{
"code": null,
"e": 7980,
"s": 7967,
"text": "cat cron.log"
}
]
|
Node.js – forEach() Method | The forEach() method in Node.js is used for iterating over a set of given array items. One can iterate over all the values of the array one-by-one using the forEach array loop.
arrayName.forEach(function)
function − The function takes input for the method that will be executed.
arrayName − Array that will be iterated.
Create a file "forEach.js" and copy the following code snippet. After creating the file, use the command "node forEach.js" to run this code.
Live Demo
// forEach() Demo Example
// Defining a vehicle array
const vehicleArray = ['bike', 'car', 'bus'];
// Iterating over the array and printing
vehicleArray.forEach(element => {
console.log(element);
});
C:\home\node>> node forEach.js
bike
car
bus
Live Demo
// forEach() Demo Example
// Defining a vehicle array
const array = [1,2,3,4,5,6,7,8,9];
var sum=0;
// Iterating over the array and printing
array.forEach(element => {
sum += element;
});
console.log(sum);
C:\home\node>> node forEach.js
45 | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "The forEach() method in Node.js is used for iterating over a set of given array items. One can iterate over all the values of the array one-by-one using the forEach array loop."
},
{
"code": null,
"e": 1267,
"s": 1239,
"text": "arrayName.forEach(function)"
},
{
"code": null,
"e": 1341,
"s": 1267,
"text": "function − The function takes input for the method that will be executed."
},
{
"code": null,
"e": 1382,
"s": 1341,
"text": "arrayName − Array that will be iterated."
},
{
"code": null,
"e": 1523,
"s": 1382,
"text": "Create a file \"forEach.js\" and copy the following code snippet. After creating the file, use the command \"node forEach.js\" to run this code."
},
{
"code": null,
"e": 1534,
"s": 1523,
"text": " Live Demo"
},
{
"code": null,
"e": 1739,
"s": 1534,
"text": "// forEach() Demo Example\n\n// Defining a vehicle array\nconst vehicleArray = ['bike', 'car', 'bus'];\n\n// Iterating over the array and printing\nvehicleArray.forEach(element => {\n console.log(element);\n});"
},
{
"code": null,
"e": 1783,
"s": 1739,
"text": "C:\\home\\node>> node forEach.js\nbike\ncar\nbus"
},
{
"code": null,
"e": 1794,
"s": 1783,
"text": " Live Demo"
},
{
"code": null,
"e": 2007,
"s": 1794,
"text": "// forEach() Demo Example\n\n// Defining a vehicle array\nconst array = [1,2,3,4,5,6,7,8,9];\n\nvar sum=0;\n\n// Iterating over the array and printing\narray.forEach(element => {\n sum += element;\n});\n\nconsole.log(sum);"
},
{
"code": null,
"e": 2041,
"s": 2007,
"text": "C:\\home\\node>> node forEach.js\n45"
}
]
|
PostgreSQL - COUNT() Function - GeeksforGeeks | 01 Jun, 2020
The COUNT() function is an aggregate function that enables users to get the number of rows that match a particular requirement of a query.Depending upon the user requirements the COUNT() function can have the following syntaxes:
Syntax: COUNT(*)
Returns: All rows including NULL and Duplicates
Syntax: COUNT(column)
Returns: All rows except NULL.
Syntax: COUNT(DISTINCT column)
Returns: All rows without NULL and Duplicates
The COUNT() function is used with the SELECT statement.
For examples we will be using the sample database (ie, dvdrental).Example 1:In this example we will use the COUNT(*) function to get the number of transactions in the payment table using the command below:
SELECT
COUNT(*)
FROM
payment;
Output:
Example 2:In this example we will query for the distinct amounts which customers paid, using the COUNT(DISTINCT column) function as shown below:
SELECT
COUNT (DISTINCT amount)
FROM
payment;
Output:
Example 3:Here we will be using the COUNT() function to get the details of customers who have made more than 40 payments:
SELECT
customer_id,
COUNT (customer_id)
FROM
payment
GROUP BY
customer_id
HAVING
COUNT (customer_id) > 40;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - Function Returning A Table
PostgreSQL - For Loops
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Interval Data Type
PostgreSQL - Cursor
How to use PostgreSQL Database in Django? | [
{
"code": null,
"e": 28000,
"s": 27972,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 28229,
"s": 28000,
"text": "The COUNT() function is an aggregate function that enables users to get the number of rows that match a particular requirement of a query.Depending upon the user requirements the COUNT() function can have the following syntaxes:"
},
{
"code": null,
"e": 28427,
"s": 28229,
"text": "Syntax: COUNT(*)\nReturns: All rows including NULL and Duplicates\n\nSyntax: COUNT(column)\nReturns: All rows except NULL.\n\nSyntax: COUNT(DISTINCT column)\nReturns: All rows without NULL and Duplicates"
},
{
"code": null,
"e": 28483,
"s": 28427,
"text": "The COUNT() function is used with the SELECT statement."
},
{
"code": null,
"e": 28689,
"s": 28483,
"text": "For examples we will be using the sample database (ie, dvdrental).Example 1:In this example we will use the COUNT(*) function to get the number of transactions in the payment table using the command below:"
},
{
"code": null,
"e": 28725,
"s": 28689,
"text": "SELECT\n COUNT(*)\nFROM\n payment;"
},
{
"code": null,
"e": 28733,
"s": 28725,
"text": "Output:"
},
{
"code": null,
"e": 28878,
"s": 28733,
"text": "Example 2:In this example we will query for the distinct amounts which customers paid, using the COUNT(DISTINCT column) function as shown below:"
},
{
"code": null,
"e": 28931,
"s": 28878,
"text": "SELECT\n COUNT (DISTINCT amount)\nFROM\n payment;"
},
{
"code": null,
"e": 28939,
"s": 28931,
"text": "Output:"
},
{
"code": null,
"e": 29061,
"s": 28939,
"text": "Example 3:Here we will be using the COUNT() function to get the details of customers who have made more than 40 payments:"
},
{
"code": null,
"e": 29188,
"s": 29061,
"text": "SELECT\n customer_id,\n COUNT (customer_id)\nFROM\n payment\nGROUP BY\n customer_id\nHAVING\n COUNT (customer_id) > 40;"
},
{
"code": null,
"e": 29196,
"s": 29188,
"text": "Output:"
},
{
"code": null,
"e": 29227,
"s": 29196,
"text": "postgreSQL-aggregate-functions"
},
{
"code": null,
"e": 29238,
"s": 29227,
"text": "PostgreSQL"
},
{
"code": null,
"e": 29336,
"s": 29238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29345,
"s": 29336,
"text": "Comments"
},
{
"code": null,
"e": 29358,
"s": 29345,
"text": "Old Comments"
},
{
"code": null,
"e": 29390,
"s": 29358,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 29417,
"s": 29390,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 29457,
"s": 29417,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 29480,
"s": 29457,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 29535,
"s": 29480,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 29569,
"s": 29535,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 29593,
"s": 29569,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 29625,
"s": 29593,
"text": "PostgreSQL - Interval Data Type"
},
{
"code": null,
"e": 29645,
"s": 29625,
"text": "PostgreSQL - Cursor"
}
]
|
Advantages and Disadvantages of Function Overloading in C++ - GeeksforGeeks | 23 Mar, 2021
Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions.
Advantages of function overloading are as follows:
The main advantage of function overloading is that it improves code readability and allows code reusability.
The use of function overloading is to save memory space, consistency, and readability.
It speeds up the execution of the program
Code maintenance also becomes easy.
Function overloading brings flexibility to code.
The function can perform different operations and hence it eliminates the use of different function names for the same kind of operations.
Disadvantage of function overloading are as follows:
Function declarations that differ only in the return type cannot be overloaded
Illustration:
int fun();
float fun();
It gives an error because the function cannot be overloaded by return type only.
Member function declarations with the same name and the same parameter types cannot be overloaded if any of them is a static member function declaration.
The main disadvantage is that it requires the compiler to perform name mangling on the function name to include information about the argument types.
Example:
C++
// Importing input output stream files#include <iostream> using namespace std; // Methods to print // Method 1void print(int i){ // Print and display statement whenever // method 1 is called cout << " Here is int " << i << endl;} // Method 2void print(double f){ // Print and display statement whenever // method 2 is called cout << " Here is float " << f << endl;} // Method 3void print(char const* c){ // Print and display statement whenever // method 3 is called cout << " Here is char* " << c << endl;} // Method 4// Main driver methodint main(){ // Calling method 1 print(10); // Calling method 2 print(10.10); // Calling method 3 print("ten"); return 0;}
Here is int 10
Here is float 10.1
Here is char* ten
Output Explanation:
In the above example all functions that were named the 3 same but printing different to which we can perceive there were different calls been made. This can be possible because of the arguments been passed according to which the function call is executed no matter be the functions are sharing a common name. Also, remember we can overload the function by changing their signature in return type. For example, here boolean print() function can be called for all three of them.
C++-Function Overloading and Default Arguments
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
List in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n23 Mar, 2021"
},
{
"code": null,
"e": 25780,
"s": 25479,
"text": "Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions."
},
{
"code": null,
"e": 25831,
"s": 25780,
"text": "Advantages of function overloading are as follows:"
},
{
"code": null,
"e": 25940,
"s": 25831,
"text": "The main advantage of function overloading is that it improves code readability and allows code reusability."
},
{
"code": null,
"e": 26027,
"s": 25940,
"text": "The use of function overloading is to save memory space, consistency, and readability."
},
{
"code": null,
"e": 26069,
"s": 26027,
"text": "It speeds up the execution of the program"
},
{
"code": null,
"e": 26105,
"s": 26069,
"text": "Code maintenance also becomes easy."
},
{
"code": null,
"e": 26154,
"s": 26105,
"text": "Function overloading brings flexibility to code."
},
{
"code": null,
"e": 26293,
"s": 26154,
"text": "The function can perform different operations and hence it eliminates the use of different function names for the same kind of operations."
},
{
"code": null,
"e": 26346,
"s": 26293,
"text": "Disadvantage of function overloading are as follows:"
},
{
"code": null,
"e": 26425,
"s": 26346,
"text": "Function declarations that differ only in the return type cannot be overloaded"
},
{
"code": null,
"e": 26439,
"s": 26425,
"text": "Illustration:"
},
{
"code": null,
"e": 26463,
"s": 26439,
"text": "int fun();\nfloat fun();"
},
{
"code": null,
"e": 26545,
"s": 26463,
"text": " It gives an error because the function cannot be overloaded by return type only."
},
{
"code": null,
"e": 26699,
"s": 26545,
"text": "Member function declarations with the same name and the same parameter types cannot be overloaded if any of them is a static member function declaration."
},
{
"code": null,
"e": 26849,
"s": 26699,
"text": "The main disadvantage is that it requires the compiler to perform name mangling on the function name to include information about the argument types."
},
{
"code": null,
"e": 26858,
"s": 26849,
"text": "Example:"
},
{
"code": null,
"e": 26862,
"s": 26858,
"text": "C++"
},
{
"code": "// Importing input output stream files#include <iostream> using namespace std; // Methods to print // Method 1void print(int i){ // Print and display statement whenever // method 1 is called cout << \" Here is int \" << i << endl;} // Method 2void print(double f){ // Print and display statement whenever // method 2 is called cout << \" Here is float \" << f << endl;} // Method 3void print(char const* c){ // Print and display statement whenever // method 3 is called cout << \" Here is char* \" << c << endl;} // Method 4// Main driver methodint main(){ // Calling method 1 print(10); // Calling method 2 print(10.10); // Calling method 3 print(\"ten\"); return 0;}",
"e": 27587,
"s": 26862,
"text": null
},
{
"code": null,
"e": 27642,
"s": 27587,
"text": " Here is int 10\n Here is float 10.1\n Here is char* ten"
},
{
"code": null,
"e": 27662,
"s": 27642,
"text": "Output Explanation:"
},
{
"code": null,
"e": 28139,
"s": 27662,
"text": "In the above example all functions that were named the 3 same but printing different to which we can perceive there were different calls been made. This can be possible because of the arguments been passed according to which the function call is executed no matter be the functions are sharing a common name. Also, remember we can overload the function by changing their signature in return type. For example, here boolean print() function can be called for all three of them."
},
{
"code": null,
"e": 28186,
"s": 28139,
"text": "C++-Function Overloading and Default Arguments"
},
{
"code": null,
"e": 28190,
"s": 28186,
"text": "C++"
},
{
"code": null,
"e": 28194,
"s": 28190,
"text": "CPP"
},
{
"code": null,
"e": 28292,
"s": 28194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28320,
"s": 28292,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28340,
"s": 28320,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28373,
"s": 28340,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28397,
"s": 28373,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28422,
"s": 28397,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28446,
"s": 28422,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 28490,
"s": 28446,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28543,
"s": 28490,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 28579,
"s": 28543,
"text": "Convert string to char array in C++"
}
]
|
Data compression in SAP HANA | In SAP HANA, there are various methods and algorithms that you can use to store data in Column based structure- Dictionary Compressed, Run Length Compressed and many more.
In Dictionary Compressed, cells are stored in form of numbers in tables and numeral cells are always performance optimized as compared to characters.
In Run length compressed, it saves the multiplier with cell value in numerical format and multiplier shows repetitive value in the table.
Compression is calculated using Compression factor. Compression factor refers to the ratio of the uncompressed data size to the compressed data size in SAP HANA.
In SAP HANA, Compression is performed and calculations are done as part of the delta merge operation. If you create an empty column table, no compression is applied initially as the database cannot know which method is most appropriate. As you start to insert data into the table and the delta merge operation starts being executed at regular intervals, data compression is automatically (re)evaluated and optimized.
Automatic compression optimization is ensured by the parameter active in the optimize_compression section of the index server.ini configuration file. This parameter must have the value yes.
To find compression details, you need to first load the table into memory. You can also load a table using SQL command. Open the SQL console and execute the following statement −
LOAD <table_name>
UNLOAD <table_name>
Note that when you load a table, it loads the complete data and also delta storage into the main memory of SAP HANA system.
To perform data compression, run the following SQL command to check data compression properties.
SELECT SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, COMPRESSION_TYPE, LOADED from
PUBLIC.M_CS_COLUMNS where SCHEMA_NAME = '<your_schema>' and TABLE_NAME = '<your_table> | [
{
"code": null,
"e": 1234,
"s": 1062,
"text": "In SAP HANA, there are various methods and algorithms that you can use to store data in Column based structure- Dictionary Compressed, Run Length Compressed and many more."
},
{
"code": null,
"e": 1384,
"s": 1234,
"text": "In Dictionary Compressed, cells are stored in form of numbers in tables and numeral cells are always performance optimized as compared to characters."
},
{
"code": null,
"e": 1522,
"s": 1384,
"text": "In Run length compressed, it saves the multiplier with cell value in numerical format and multiplier shows repetitive value in the table."
},
{
"code": null,
"e": 1684,
"s": 1522,
"text": "Compression is calculated using Compression factor. Compression factor refers to the ratio of the uncompressed data size to the compressed data size in SAP HANA."
},
{
"code": null,
"e": 2101,
"s": 1684,
"text": "In SAP HANA, Compression is performed and calculations are done as part of the delta merge operation. If you create an empty column table, no compression is applied initially as the database cannot know which method is most appropriate. As you start to insert data into the table and the delta merge operation starts being executed at regular intervals, data compression is automatically (re)evaluated and optimized."
},
{
"code": null,
"e": 2291,
"s": 2101,
"text": "Automatic compression optimization is ensured by the parameter active in the optimize_compression section of the index server.ini configuration file. This parameter must have the value yes."
},
{
"code": null,
"e": 2470,
"s": 2291,
"text": "To find compression details, you need to first load the table into memory. You can also load a table using SQL command. Open the SQL console and execute the following statement −"
},
{
"code": null,
"e": 2508,
"s": 2470,
"text": "LOAD <table_name>\nUNLOAD <table_name>"
},
{
"code": null,
"e": 2632,
"s": 2508,
"text": "Note that when you load a table, it loads the complete data and also delta storage into the main memory of SAP HANA system."
},
{
"code": null,
"e": 2729,
"s": 2632,
"text": "To perform data compression, run the following SQL command to check data compression properties."
},
{
"code": null,
"e": 2891,
"s": 2729,
"text": "SELECT SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, COMPRESSION_TYPE, LOADED from\nPUBLIC.M_CS_COLUMNS where SCHEMA_NAME = '<your_schema>' and TABLE_NAME = '<your_table>"
}
]
|
CopyOnWriteArrayList in Java - GeeksforGeeks | 05 Feb, 2021
CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to be used in a concurrent environment.
Here are few points about CopyOnWriteArrayList:
As the name indicates, CopyOnWriteArrayList creates a Cloned copy of underlying ArrayList, for every update operation at a certain point both will be synchronized automatically, which is taken care of by JVM. Therefore, there is no effect for threads that are performing read operation.
It is costly to use because for every update operation a cloned copy will be created. Hence, CopyOnWriteArrayList is the best choice if our frequent operation is read operation.
The underlined data structure is a grow-able array.
It is a thread-safe version of ArrayList.
Insertion is preserved, duplicates, null, and heterogeneous Objects are allowed.
The main important point about CopyOnWriteArrayList is the Iterator of CopyOnWriteArrayList can not perform remove operation otherwise we get Run-time exception saying UnsupportedOperationException. add() and set() methods on CopyOnWriteArrayList iterator also throws UnsupportedOperationException. Also Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException.
Declaration:
public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable
Here, E is the type of elements held in this collection.
Note: The class implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
Constructors:
1. CopyOnWriteArrayList(): Creates an empty list.
CopyOnWriteArrayList c = new CopyOnWriteArrayList();
2. CopyOnWriteArrayList(Collection obj): Creates a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator.
CopyOnWriteArrayList c = new CopyOnWriteArrayList(Collection obj);
3. CopyOnWriteArrayList(Object[] obj);: Creates a list holding a copy of the given array.
CopyOnWriteArrayList c = new CopyOnWriteArrayList(Object[] obj);
Example:
Java
// Java program to illustrate// CopyOnWriteArrayList classimport java.util.*;import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentDemo extends Thread { static CopyOnWriteArrayList<String> l = new CopyOnWriteArrayList<String>(); public void run() { // Child thread trying to // add new element in the // Collection object l.add("D"); } public static void main(String[] args) throws InterruptedException { l.add("A"); l.add("B"); l.add("c"); // We create a child thread // that is going to modify // ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.run(); Thread.sleep(1000); // Now we iterate through // the ArrayList and get // exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}
A
B
c
D
[A, B, c, D]
Iterating over CopyOnWriteArrayList: We can iterate over CopyOnWriteArrayList using iterator() method. The important point to be noted is that the iterator we create is an immutable snapshot of the original list. Because of this property, we can see that GfG is not printed at the first iteration.
Java
// Java program to illustrate// CopyOnWriteArrayList classimport java.io.*;import java.util.*;import java.util.concurrent.*; class Demo { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); // Initial Iterator Iterator itr = list.iterator(); list.add("GfG"); System.out.println("List contains: "); while (itr.hasNext()) System.out.println(itr.next()); // iterator after adding an element itr = list.iterator(); System.out.println("List contains:"); while (itr.hasNext()) System.out.println(itr.next()); }}
List contains:
List contains:
GfG
Methods of CopyOnWriteArrayList:
METHOD
DESCRIPTION
Methods inherited from interface java.util.Collection:
METHOD
DESCRIPTION
Note: We should use CopyOnWriteArrayList when we prefer to use a data structure similar to ArrayList in a concurrent environment.
Must Read:
Difference between ArrayList and CopyOnWriteArrayList
vinaykumar54
randhish79
rahulcooldude05
Ganeshchowdharysadanala
ankitkadam11
Java - util package
Java-ArrayList
Java-Collections
Java-CopyOnWriteArrayList
java-list
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
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 23842,
"s": 23814,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 24179,
"s": 23842,
"text": "CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to be used in a concurrent environment. "
},
{
"code": null,
"e": 24228,
"s": 24179,
"text": "Here are few points about CopyOnWriteArrayList: "
},
{
"code": null,
"e": 24515,
"s": 24228,
"text": "As the name indicates, CopyOnWriteArrayList creates a Cloned copy of underlying ArrayList, for every update operation at a certain point both will be synchronized automatically, which is taken care of by JVM. Therefore, there is no effect for threads that are performing read operation."
},
{
"code": null,
"e": 24693,
"s": 24515,
"text": "It is costly to use because for every update operation a cloned copy will be created. Hence, CopyOnWriteArrayList is the best choice if our frequent operation is read operation."
},
{
"code": null,
"e": 24745,
"s": 24693,
"text": "The underlined data structure is a grow-able array."
},
{
"code": null,
"e": 24787,
"s": 24745,
"text": "It is a thread-safe version of ArrayList."
},
{
"code": null,
"e": 24868,
"s": 24787,
"text": "Insertion is preserved, duplicates, null, and heterogeneous Objects are allowed."
},
{
"code": null,
"e": 25255,
"s": 24868,
"text": "The main important point about CopyOnWriteArrayList is the Iterator of CopyOnWriteArrayList can not perform remove operation otherwise we get Run-time exception saying UnsupportedOperationException. add() and set() methods on CopyOnWriteArrayList iterator also throws UnsupportedOperationException. Also Iterator of CopyOnWriteArrayList will never throw ConcurrentModificationException."
},
{
"code": null,
"e": 25268,
"s": 25255,
"text": "Declaration:"
},
{
"code": null,
"e": 25378,
"s": 25268,
"text": "public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable"
},
{
"code": null,
"e": 25435,
"s": 25378,
"text": "Here, E is the type of elements held in this collection."
},
{
"code": null,
"e": 25549,
"s": 25435,
"text": "Note: The class implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces."
},
{
"code": null,
"e": 25563,
"s": 25549,
"text": "Constructors:"
},
{
"code": null,
"e": 25613,
"s": 25563,
"text": "1. CopyOnWriteArrayList(): Creates an empty list."
},
{
"code": null,
"e": 25666,
"s": 25613,
"text": "CopyOnWriteArrayList c = new CopyOnWriteArrayList();"
},
{
"code": null,
"e": 25837,
"s": 25666,
"text": "2. CopyOnWriteArrayList(Collection obj): Creates a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator."
},
{
"code": null,
"e": 25904,
"s": 25837,
"text": "CopyOnWriteArrayList c = new CopyOnWriteArrayList(Collection obj);"
},
{
"code": null,
"e": 25994,
"s": 25904,
"text": "3. CopyOnWriteArrayList(Object[] obj);: Creates a list holding a copy of the given array."
},
{
"code": null,
"e": 26059,
"s": 25994,
"text": "CopyOnWriteArrayList c = new CopyOnWriteArrayList(Object[] obj);"
},
{
"code": null,
"e": 26069,
"s": 26059,
"text": "Example: "
},
{
"code": null,
"e": 26074,
"s": 26069,
"text": "Java"
},
{
"code": "// Java program to illustrate// CopyOnWriteArrayList classimport java.util.*;import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentDemo extends Thread { static CopyOnWriteArrayList<String> l = new CopyOnWriteArrayList<String>(); public void run() { // Child thread trying to // add new element in the // Collection object l.add(\"D\"); } public static void main(String[] args) throws InterruptedException { l.add(\"A\"); l.add(\"B\"); l.add(\"c\"); // We create a child thread // that is going to modify // ArrayList l. ConcurrentDemo t = new ConcurrentDemo(); t.run(); Thread.sleep(1000); // Now we iterate through // the ArrayList and get // exception. Iterator itr = l.iterator(); while (itr.hasNext()) { String s = (String)itr.next(); System.out.println(s); Thread.sleep(1000); } System.out.println(l); }}",
"e": 27109,
"s": 26074,
"text": null
},
{
"code": null,
"e": 27131,
"s": 27109,
"text": "A\nB\nc\nD\n[A, B, c, D]\n"
},
{
"code": null,
"e": 27431,
"s": 27133,
"text": "Iterating over CopyOnWriteArrayList: We can iterate over CopyOnWriteArrayList using iterator() method. The important point to be noted is that the iterator we create is an immutable snapshot of the original list. Because of this property, we can see that GfG is not printed at the first iteration."
},
{
"code": null,
"e": 27436,
"s": 27431,
"text": "Java"
},
{
"code": "// Java program to illustrate// CopyOnWriteArrayList classimport java.io.*;import java.util.*;import java.util.concurrent.*; class Demo { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); // Initial Iterator Iterator itr = list.iterator(); list.add(\"GfG\"); System.out.println(\"List contains: \"); while (itr.hasNext()) System.out.println(itr.next()); // iterator after adding an element itr = list.iterator(); System.out.println(\"List contains:\"); while (itr.hasNext()) System.out.println(itr.next()); }}",
"e": 28112,
"s": 27436,
"text": null
},
{
"code": null,
"e": 28148,
"s": 28112,
"text": "List contains: \nList contains:\nGfG\n"
},
{
"code": null,
"e": 28181,
"s": 28148,
"text": "Methods of CopyOnWriteArrayList:"
},
{
"code": null,
"e": 28188,
"s": 28181,
"text": "METHOD"
},
{
"code": null,
"e": 28200,
"s": 28188,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 28255,
"s": 28200,
"text": "Methods inherited from interface java.util.Collection:"
},
{
"code": null,
"e": 28262,
"s": 28255,
"text": "METHOD"
},
{
"code": null,
"e": 28274,
"s": 28262,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 28404,
"s": 28274,
"text": "Note: We should use CopyOnWriteArrayList when we prefer to use a data structure similar to ArrayList in a concurrent environment."
},
{
"code": null,
"e": 28415,
"s": 28404,
"text": "Must Read:"
},
{
"code": null,
"e": 28469,
"s": 28415,
"text": "Difference between ArrayList and CopyOnWriteArrayList"
},
{
"code": null,
"e": 28482,
"s": 28469,
"text": "vinaykumar54"
},
{
"code": null,
"e": 28493,
"s": 28482,
"text": "randhish79"
},
{
"code": null,
"e": 28509,
"s": 28493,
"text": "rahulcooldude05"
},
{
"code": null,
"e": 28533,
"s": 28509,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 28546,
"s": 28533,
"text": "ankitkadam11"
},
{
"code": null,
"e": 28566,
"s": 28546,
"text": "Java - util package"
},
{
"code": null,
"e": 28581,
"s": 28566,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 28598,
"s": 28581,
"text": "Java-Collections"
},
{
"code": null,
"e": 28624,
"s": 28598,
"text": "Java-CopyOnWriteArrayList"
},
{
"code": null,
"e": 28634,
"s": 28624,
"text": "java-list"
},
{
"code": null,
"e": 28639,
"s": 28634,
"text": "Java"
},
{
"code": null,
"e": 28644,
"s": 28639,
"text": "Java"
},
{
"code": null,
"e": 28661,
"s": 28644,
"text": "Java-Collections"
},
{
"code": null,
"e": 28759,
"s": 28661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28768,
"s": 28759,
"text": "Comments"
},
{
"code": null,
"e": 28781,
"s": 28768,
"text": "Old Comments"
},
{
"code": null,
"e": 28796,
"s": 28781,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28840,
"s": 28796,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28862,
"s": 28840,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28898,
"s": 28862,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 28923,
"s": 28898,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28955,
"s": 28923,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28985,
"s": 28955,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29004,
"s": 28985,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29055,
"s": 29004,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
]
|
How can we implement auto-complete JComboBox in Java?
| A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener, and ItemListener interfaces when the user actions on a combo box.
We can implement auto-complete JComboBox when the user types an input value from a keyboard by using customization of a combo box (AutoCompleteComboBox) by extending the JComboBox class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class AutoCompleteComboBoxTest extends JFrame {
private JComboBox comboBox;
public AutoCompleteComboBoxTest() {
setTitle("AutoCompleteComboBox");
String[] countries = new String[] {"india", "australia", "newzealand", "england", "germany",
"france", "ireland", "southafrica", "bangladesh", "holland", "america"};
comboBox = new AutoCompleteComboBox(countries);
add(comboBox, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String []args) {
new AutoCompleteComboBoxTest();
}
}
// Implementtion of AutoCompleteComboBox
class AutoCompleteComboBox extends JComboBox {
public int caretPos = 0;
public JTextField tfield = null;
public AutoCompleteComboBox(final Object countries[]) {
super(countries);
setEditor(new BasicComboBoxEditor());
setEditable(true);
}
public void setSelectedIndex(int index) {
super.setSelectedIndex(index);
tfield.setText(getItemAt(index).toString());
tfield.setSelectionEnd(caretPos + tfield.getText().length());
tfield.moveCaretPosition(caretPos);
}
public void setEditor(ComboBoxEditor editor) {
super.setEditor(editor);
if(editor.getEditorComponent() instanceof JTextField) {
tfield = (JTextField) editor.getEditorComponent();
tfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
char key = ke.getKeyChar();
if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
caretPos = tfield.getCaretPosition();
String text="";
try {
text = tfield.getText(0, caretPos);
} catch (javax.swing.text.BadLocationException e) {
e.printStackTrace();
}
for (int i=0; i < getItemCount(); i++) {
String element = (String) getItemAt(i);
if (element.startsWith(text)) {
setSelectedIndex(i);
return;
}
}
}
});
}
}
} | [
{
"code": null,
"e": 1335,
"s": 1062,
"text": "A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener, and ItemListener interfaces when the user actions on a combo box."
},
{
"code": null,
"e": 1522,
"s": 1335,
"text": "We can implement auto-complete JComboBox when the user types an input value from a keyboard by using customization of a combo box (AutoCompleteComboBox) by extending the JComboBox class."
},
{
"code": null,
"e": 3879,
"s": 1522,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.plaf.basic.*;\npublic class AutoCompleteComboBoxTest extends JFrame {\n private JComboBox comboBox;\n public AutoCompleteComboBoxTest() {\n setTitle(\"AutoCompleteComboBox\");\n String[] countries = new String[] {\"india\", \"australia\", \"newzealand\", \"england\", \"germany\",\n\"france\", \"ireland\", \"southafrica\", \"bangladesh\", \"holland\", \"america\"};\n comboBox = new AutoCompleteComboBox(countries);\n add(comboBox, BorderLayout.NORTH);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String []args) {\n new AutoCompleteComboBoxTest();\n }\n}\n // Implementtion of AutoCompleteComboBox\nclass AutoCompleteComboBox extends JComboBox {\n public int caretPos = 0;\n public JTextField tfield = null;\n public AutoCompleteComboBox(final Object countries[]) {\n super(countries);\n setEditor(new BasicComboBoxEditor());\n setEditable(true);\n }\n public void setSelectedIndex(int index) {\n super.setSelectedIndex(index);\n tfield.setText(getItemAt(index).toString());\n tfield.setSelectionEnd(caretPos + tfield.getText().length());\n tfield.moveCaretPosition(caretPos);\n }\n public void setEditor(ComboBoxEditor editor) {\n super.setEditor(editor);\n if(editor.getEditorComponent() instanceof JTextField) {\n tfield = (JTextField) editor.getEditorComponent();\n tfield.addKeyListener(new KeyAdapter() {\n public void keyReleased(KeyEvent ke) {\n char key = ke.getKeyChar();\n if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;\n caretPos = tfield.getCaretPosition();\n String text=\"\";\n try {\n text = tfield.getText(0, caretPos);\n } catch (javax.swing.text.BadLocationException e) {\n e.printStackTrace();\n }\n for (int i=0; i < getItemCount(); i++) {\n String element = (String) getItemAt(i);\n if (element.startsWith(text)) {\n setSelectedIndex(i);\n return;\n }\n }\n }\n });\n }\n }\n}"
}
]
|
How to Create and Modify Properties File Form Java Program in Text and XML Format? - GeeksforGeeks | 21 Dec, 2021
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article, let us see how to create properties file using Java programs.
Java API got java.util.Properties class and it has several utility stores() methods to store properties in either Text or XML format. In order to store property in text format, Store() method can be used. storeToXML() is used to make in XML format.
store() method took two parameters like Output Stream and Comments.
Text format creation:
Let us see how to create a properties file in a text format. As we are creating properties contents, a valid file path location needs to be given.
Java
import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties; public class CreationOfTextOrientedProperties { public static void main(String args[]) throws FileNotFoundException, IOException { // Creating properties files from Java program Properties properties = new Properties(); // In the name of userCreated.properties, in the // current directory location, the file is created FileOutputStream fileOutputStream = new FileOutputStream( "userCreated.properties"); // As an example, given steps how // to keep username and password properties.setProperty("username", "value1"); properties.setProperty("password", "value2"); // writing properties into properties file // from Java As we are writing text format, // store() method is used properties.store( fileOutputStream, "Sample way of creating Properties file from Java program"); fileOutputStream.close(); }}
Output:
We are using store() to save the properties file in text format. As key-value pairs, they are set. i.e. key = value. Other than that, all are considered as comments and hence with # symbol, comments are placed.
Usage of properties in text format is helpful in many instances when the property contents are less, and the team of developers is often changing, and end-users are on the Non-IT side.
XML format creation:
In many instances, XML is needed which provides an easy-to-understand and efficient format for storing important sensitive information. Extensible Markup Language (XML) is a markup language, and it is having a set of rules for encoding documents, and they are understandable in both human-readable and machine-readable format. Here, let us see how to create via Java program
Java
import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties; public class CreationOfXMLOrientedProperties { public static void main(String args[]) throws FileNotFoundException, IOException { // Creating properties files from Java program Properties properties = new Properties(); // In the name of userCreated.xml, in the current // directory location, the file is created FileOutputStream fileOutputStream = new FileOutputStream("userCreated.xml"); // As an example, given steps how to keep username // and password properties.setProperty("username", "value1"); properties.setProperty("password", "value2"); // writing properties into properties file // from Java As we are writing in XML format, // storeToXML() method is used properties.storeToXML( fileOutputStream, "Sample way of creating Properties file from Java program"); fileOutputStream.close(); }}
Output:
If we check out the output of XML, it has an equal opening and closing of entries.
The one created via java programs also has the same structure. It has started to have with <properties> and end with </properties>. Other than key-value pair sets, the text is treated as comments and hence they are inside the comment tags. Properties files are having key values only and here also it is declared within “entry” tags along with “key=” which means separate entries are given for each and every key-value pair.
Whenever the properties file contents are huge and having sensitive information like banking transactions, financial data, etc., it is better to go in XML format only.
A convenient way of converting XML contents to Read-only Text Mode way
Java
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.InvalidPropertiesFormatException;import java.util.Properties; public class ConvertXMLToTextOrientedProperties { public static void main(String[] args) throws InvalidPropertiesFormatException, IOException { String outputPropertiesFile = "sampleapplication.properties"; String inputXmlFile = "sampleapplicationProperties.xml"; // Input XML File which contains // necessary information InputStream inputStream = new FileInputStream(inputXmlFile); // Output properties File OutputStream outputStream = new FileOutputStream(outputPropertiesFile); Properties properties = new Properties(); // Load XML file that has necessary information properties.loadFromXML(inputStream); // Store to properties file via this way properties.store( outputStream, "Converted from sampleapplicationProperties.xml"); // For sample testing let us get username--It is // nothing but "Geek" // As it is converted to .properties file, // we can get the values in this way System.out.println(properties.get("username")); }}
Input file (sampleapplicationProperties.xml)
XML
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><comment>Elegant way of converting sampleapplicationProperties.xml to Sampleapplication.properties</comment><entry key="username">Geek</entry> <entry key="password">XXXXWeldoneXXXX</entry></properties>
Generated Output file(sampleapplication.properties)
And also as we have, System.out.println(properties.get(“username”)); , it displays
“Geek” as output. So loadFromXML() helps to load the XML file and converts that to text-oriented properties file by means of the store() and also as got converted, we can get the property values easily.
Conclusion :
In this article, we have seen the ways of creation of properties files from java programs. Enjoy them to your convenience. They are helpful in any part of the software project as properties files are key files that hold sensitive information and also as they are in key-value pairs either as text or XML format, dynamic usage is seen, and at any point of time, we can modify them easily too.
sumitgumber28
Java-Files
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 24090,
"s": 24062,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 24504,
"s": 24090,
"text": "Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article, let us see how to create properties file using Java programs."
},
{
"code": null,
"e": 24754,
"s": 24504,
"text": "Java API got java.util.Properties class and it has several utility stores() methods to store properties in either Text or XML format. In order to store property in text format, Store() method can be used. storeToXML() is used to make in XML format."
},
{
"code": null,
"e": 24822,
"s": 24754,
"text": "store() method took two parameters like Output Stream and Comments."
},
{
"code": null,
"e": 24844,
"s": 24822,
"text": "Text format creation:"
},
{
"code": null,
"e": 24991,
"s": 24844,
"text": "Let us see how to create a properties file in a text format. As we are creating properties contents, a valid file path location needs to be given."
},
{
"code": null,
"e": 24996,
"s": 24991,
"text": "Java"
},
{
"code": "import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties; public class CreationOfTextOrientedProperties { public static void main(String args[]) throws FileNotFoundException, IOException { // Creating properties files from Java program Properties properties = new Properties(); // In the name of userCreated.properties, in the // current directory location, the file is created FileOutputStream fileOutputStream = new FileOutputStream( \"userCreated.properties\"); // As an example, given steps how // to keep username and password properties.setProperty(\"username\", \"value1\"); properties.setProperty(\"password\", \"value2\"); // writing properties into properties file // from Java As we are writing text format, // store() method is used properties.store( fileOutputStream, \"Sample way of creating Properties file from Java program\"); fileOutputStream.close(); }}",
"e": 26105,
"s": 24996,
"text": null
},
{
"code": null,
"e": 26113,
"s": 26105,
"text": "Output:"
},
{
"code": null,
"e": 26324,
"s": 26113,
"text": "We are using store() to save the properties file in text format. As key-value pairs, they are set. i.e. key = value. Other than that, all are considered as comments and hence with # symbol, comments are placed."
},
{
"code": null,
"e": 26509,
"s": 26324,
"text": "Usage of properties in text format is helpful in many instances when the property contents are less, and the team of developers is often changing, and end-users are on the Non-IT side."
},
{
"code": null,
"e": 26530,
"s": 26509,
"text": "XML format creation:"
},
{
"code": null,
"e": 26905,
"s": 26530,
"text": "In many instances, XML is needed which provides an easy-to-understand and efficient format for storing important sensitive information. Extensible Markup Language (XML) is a markup language, and it is having a set of rules for encoding documents, and they are understandable in both human-readable and machine-readable format. Here, let us see how to create via Java program"
},
{
"code": null,
"e": 26910,
"s": 26905,
"text": "Java"
},
{
"code": "import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties; public class CreationOfXMLOrientedProperties { public static void main(String args[]) throws FileNotFoundException, IOException { // Creating properties files from Java program Properties properties = new Properties(); // In the name of userCreated.xml, in the current // directory location, the file is created FileOutputStream fileOutputStream = new FileOutputStream(\"userCreated.xml\"); // As an example, given steps how to keep username // and password properties.setProperty(\"username\", \"value1\"); properties.setProperty(\"password\", \"value2\"); // writing properties into properties file // from Java As we are writing in XML format, // storeToXML() method is used properties.storeToXML( fileOutputStream, \"Sample way of creating Properties file from Java program\"); fileOutputStream.close(); }}",
"e": 27994,
"s": 26910,
"text": null
},
{
"code": null,
"e": 28002,
"s": 27994,
"text": "Output:"
},
{
"code": null,
"e": 28085,
"s": 28002,
"text": "If we check out the output of XML, it has an equal opening and closing of entries."
},
{
"code": null,
"e": 28510,
"s": 28085,
"text": "The one created via java programs also has the same structure. It has started to have with <properties> and end with </properties>. Other than key-value pair sets, the text is treated as comments and hence they are inside the comment tags. Properties files are having key values only and here also it is declared within “entry” tags along with “key=” which means separate entries are given for each and every key-value pair."
},
{
"code": null,
"e": 28679,
"s": 28510,
"text": "Whenever the properties file contents are huge and having sensitive information like banking transactions, financial data, etc., it is better to go in XML format only. "
},
{
"code": null,
"e": 28750,
"s": 28679,
"text": "A convenient way of converting XML contents to Read-only Text Mode way"
},
{
"code": null,
"e": 28755,
"s": 28750,
"text": "Java"
},
{
"code": "import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.InvalidPropertiesFormatException;import java.util.Properties; public class ConvertXMLToTextOrientedProperties { public static void main(String[] args) throws InvalidPropertiesFormatException, IOException { String outputPropertiesFile = \"sampleapplication.properties\"; String inputXmlFile = \"sampleapplicationProperties.xml\"; // Input XML File which contains // necessary information InputStream inputStream = new FileInputStream(inputXmlFile); // Output properties File OutputStream outputStream = new FileOutputStream(outputPropertiesFile); Properties properties = new Properties(); // Load XML file that has necessary information properties.loadFromXML(inputStream); // Store to properties file via this way properties.store( outputStream, \"Converted from sampleapplicationProperties.xml\"); // For sample testing let us get username--It is // nothing but \"Geek\" // As it is converted to .properties file, // we can get the values in this way System.out.println(properties.get(\"username\")); }}",
"e": 30128,
"s": 28755,
"text": null
},
{
"code": null,
"e": 30173,
"s": 30128,
"text": "Input file (sampleapplicationProperties.xml)"
},
{
"code": null,
"e": 30177,
"s": 30173,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\"><properties><comment>Elegant way of converting sampleapplicationProperties.xml to Sampleapplication.properties</comment><entry key=\"username\">Geek</entry> <entry key=\"password\">XXXXWeldoneXXXX</entry></properties>",
"e": 30501,
"s": 30177,
"text": null
},
{
"code": null,
"e": 30553,
"s": 30501,
"text": "Generated Output file(sampleapplication.properties)"
},
{
"code": null,
"e": 30636,
"s": 30553,
"text": "And also as we have, System.out.println(properties.get(“username”)); , it displays"
},
{
"code": null,
"e": 30839,
"s": 30636,
"text": "“Geek” as output. So loadFromXML() helps to load the XML file and converts that to text-oriented properties file by means of the store() and also as got converted, we can get the property values easily."
},
{
"code": null,
"e": 30852,
"s": 30839,
"text": "Conclusion :"
},
{
"code": null,
"e": 31244,
"s": 30852,
"text": "In this article, we have seen the ways of creation of properties files from java programs. Enjoy them to your convenience. They are helpful in any part of the software project as properties files are key files that hold sensitive information and also as they are in key-value pairs either as text or XML format, dynamic usage is seen, and at any point of time, we can modify them easily too."
},
{
"code": null,
"e": 31258,
"s": 31244,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31269,
"s": 31258,
"text": "Java-Files"
},
{
"code": null,
"e": 31276,
"s": 31269,
"text": "Picked"
},
{
"code": null,
"e": 31300,
"s": 31276,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31305,
"s": 31300,
"text": "Java"
},
{
"code": null,
"e": 31324,
"s": 31305,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31329,
"s": 31324,
"text": "Java"
},
{
"code": null,
"e": 31427,
"s": 31329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31442,
"s": 31427,
"text": "Stream In Java"
},
{
"code": null,
"e": 31461,
"s": 31442,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31482,
"s": 31461,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31528,
"s": 31482,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31558,
"s": 31528,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31575,
"s": 31558,
"text": "Generics in Java"
},
{
"code": null,
"e": 31618,
"s": 31575,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31640,
"s": 31618,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 31661,
"s": 31640,
"text": "Introduction to Java"
}
]
|
C++ Program for GCD of more than two (or array) numbers? | The common divisor of two numbers are the numbers that are divisors of both of them.
For example, the divisors of 12 are 1, 2, 3, 4, 6, 12. The divisors of 18 are 1, 2, 3, 6, 9, 18. Thus, the common divisors of 12 and 18 are 1, 2, 3, 6. The greatest among these is, perhaps unsurprisingly, called the of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6.
The greatest common divisor is important for many reasons. For example, it can be used to calculate the of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as a*b*(a, b)
For example, the least common multiple of 12 and 18 is
12*18*(12, 18)=12*18*6
Input: 4, 10, 16, 14
Output: 2
GCD of two or more integers is the largest integer that can exactly divide both numbers (without a remainder).
#include <iostream>
using namespace std;
int gcd(int a,int b) {
int temp;
while(b > 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int a[] = {4, 10, 16, 14};
int n = 4;
int r = a[0];
for(int i=1; i<n; i++) {
r = gcd(r, a[i]);
}
cout << r << endl;
return 0;
}
4 | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "The common divisor of two numbers are the numbers that are divisors of both of them."
},
{
"code": null,
"e": 1509,
"s": 1147,
"text": "For example, the divisors of 12 are 1, 2, 3, 4, 6, 12. The divisors of 18 are 1, 2, 3, 6, 9, 18. Thus, the common divisors of 12 and 18 are 1, 2, 3, 6. The greatest among these is, perhaps unsurprisingly, called the of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6."
},
{
"code": null,
"e": 1783,
"s": 1509,
"text": "The greatest common divisor is important for many reasons. For example, it can be used to calculate the of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as a*b*(a, b)"
},
{
"code": null,
"e": 1861,
"s": 1783,
"text": "For example, the least common multiple of 12 and 18 is\n12*18*(12, 18)=12*18*6"
},
{
"code": null,
"e": 1892,
"s": 1861,
"text": "Input: 4, 10, 16, 14\nOutput: 2"
},
{
"code": null,
"e": 2003,
"s": 1892,
"text": "GCD of two or more integers is the largest integer that can exactly divide both numbers (without a remainder)."
},
{
"code": null,
"e": 2335,
"s": 2003,
"text": "#include <iostream>\nusing namespace std;\nint gcd(int a,int b) {\n int temp;\n while(b > 0) {\n temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\nint main() {\n int a[] = {4, 10, 16, 14};\n int n = 4;\n int r = a[0];\n for(int i=1; i<n; i++) {\n r = gcd(r, a[i]);\n }\n cout << r << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2337,
"s": 2335,
"text": "4"
}
]
|
Program to find Kth bit in n-th binary string using Python | Suppose we have two positive values n and k, now we can make a binary string S_n by using following rules −
S_1 = 0
S_1 = 0
S_i = S_i-1 concatenate "1" concatenate reverse(invert(S_i-1)) for i > 1
S_i = S_i-1 concatenate "1" concatenate reverse(invert(S_i-1)) for i > 1
Here reverse(x) returns the reversed string x, and invert(x) flips all the bits in x.
These are the example of four such strings
S_1 = "0"
S_1 = "0"
S_2 = "011"
S_2 = "011"
S_3 = "0111001"
S_3 = "0111001"
S_4 = "011100110110001"
S_4 = "011100110110001"
We have to find kth bit in S_n.
So, if the input is like n = 4 k = 10, then the output will be 1 because S_4 = "011100110110001",
so 10th bit is 1 (first bit is at position 1).
To solve this, we will follow these steps −
if k is same as 1, thenreturn 0 as string
if k is same as 1, then
return 0 as string
return 0 as string
otherwise,arr := an array with single element 0arr2 := an array with single element 1while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last
otherwise,
arr := an array with single element 0
arr := an array with single element 0
arr2 := an array with single element 1
arr2 := an array with single element 1
while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last
while k > size of arr, do
templast := copy of arr
templast := copy of arr
temp2last := copy of arr2
temp2last := copy of arr2
arr := templast concatenate 1 concatenate temp2last
arr := templast concatenate 1 concatenate temp2last
arr2 := templast concatenate 0 concatenate temp2last
arr2 := templast concatenate 0 concatenate temp2last
return k-1 th element from arr
return k-1 th element from arr
Let us see the following implementation to get better understanding −
def solve(n, k):
if k == 1:
return(str(0))
else:
arr = [0]
arr2 = [1]
while k > len(arr):
templast = arr.copy()
temp2last = arr2.copy()
arr = templast + [1] + temp2last
arr2 = templast + [0] + temp2last
return(str(arr[k-1]))
n = 4
k = 10
print(solve(n, k))
4, 10
1 | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Suppose we have two positive values n and k, now we can make a binary string S_n by using following rules −"
},
{
"code": null,
"e": 1178,
"s": 1170,
"text": "S_1 = 0"
},
{
"code": null,
"e": 1186,
"s": 1178,
"text": "S_1 = 0"
},
{
"code": null,
"e": 1259,
"s": 1186,
"text": "S_i = S_i-1 concatenate \"1\" concatenate reverse(invert(S_i-1)) for i > 1"
},
{
"code": null,
"e": 1332,
"s": 1259,
"text": "S_i = S_i-1 concatenate \"1\" concatenate reverse(invert(S_i-1)) for i > 1"
},
{
"code": null,
"e": 1418,
"s": 1332,
"text": "Here reverse(x) returns the reversed string x, and invert(x) flips all the bits in x."
},
{
"code": null,
"e": 1461,
"s": 1418,
"text": "These are the example of four such strings"
},
{
"code": null,
"e": 1471,
"s": 1461,
"text": "S_1 = \"0\""
},
{
"code": null,
"e": 1481,
"s": 1471,
"text": "S_1 = \"0\""
},
{
"code": null,
"e": 1493,
"s": 1481,
"text": "S_2 = \"011\""
},
{
"code": null,
"e": 1505,
"s": 1493,
"text": "S_2 = \"011\""
},
{
"code": null,
"e": 1521,
"s": 1505,
"text": "S_3 = \"0111001\""
},
{
"code": null,
"e": 1537,
"s": 1521,
"text": "S_3 = \"0111001\""
},
{
"code": null,
"e": 1561,
"s": 1537,
"text": "S_4 = \"011100110110001\""
},
{
"code": null,
"e": 1585,
"s": 1561,
"text": "S_4 = \"011100110110001\""
},
{
"code": null,
"e": 1617,
"s": 1585,
"text": "We have to find kth bit in S_n."
},
{
"code": null,
"e": 1762,
"s": 1617,
"text": "So, if the input is like n = 4 k = 10, then the output will be 1 because S_4 = \"011100110110001\",\nso 10th bit is 1 (first bit is at position 1)."
},
{
"code": null,
"e": 1806,
"s": 1762,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1848,
"s": 1806,
"text": "if k is same as 1, thenreturn 0 as string"
},
{
"code": null,
"e": 1872,
"s": 1848,
"text": "if k is same as 1, then"
},
{
"code": null,
"e": 1891,
"s": 1872,
"text": "return 0 as string"
},
{
"code": null,
"e": 1910,
"s": 1891,
"text": "return 0 as string"
},
{
"code": null,
"e": 2172,
"s": 1910,
"text": "otherwise,arr := an array with single element 0arr2 := an array with single element 1while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last"
},
{
"code": null,
"e": 2183,
"s": 2172,
"text": "otherwise,"
},
{
"code": null,
"e": 2221,
"s": 2183,
"text": "arr := an array with single element 0"
},
{
"code": null,
"e": 2259,
"s": 2221,
"text": "arr := an array with single element 0"
},
{
"code": null,
"e": 2298,
"s": 2259,
"text": "arr2 := an array with single element 1"
},
{
"code": null,
"e": 2337,
"s": 2298,
"text": "arr2 := an array with single element 1"
},
{
"code": null,
"e": 2514,
"s": 2337,
"text": "while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last"
},
{
"code": null,
"e": 2540,
"s": 2514,
"text": "while k > size of arr, do"
},
{
"code": null,
"e": 2564,
"s": 2540,
"text": "templast := copy of arr"
},
{
"code": null,
"e": 2588,
"s": 2564,
"text": "templast := copy of arr"
},
{
"code": null,
"e": 2614,
"s": 2588,
"text": "temp2last := copy of arr2"
},
{
"code": null,
"e": 2640,
"s": 2614,
"text": "temp2last := copy of arr2"
},
{
"code": null,
"e": 2692,
"s": 2640,
"text": "arr := templast concatenate 1 concatenate temp2last"
},
{
"code": null,
"e": 2744,
"s": 2692,
"text": "arr := templast concatenate 1 concatenate temp2last"
},
{
"code": null,
"e": 2797,
"s": 2744,
"text": "arr2 := templast concatenate 0 concatenate temp2last"
},
{
"code": null,
"e": 2850,
"s": 2797,
"text": "arr2 := templast concatenate 0 concatenate temp2last"
},
{
"code": null,
"e": 2881,
"s": 2850,
"text": "return k-1 th element from arr"
},
{
"code": null,
"e": 2912,
"s": 2881,
"text": "return k-1 th element from arr"
},
{
"code": null,
"e": 2982,
"s": 2912,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3311,
"s": 2982,
"text": "def solve(n, k):\n if k == 1:\n return(str(0))\n else:\n arr = [0]\n arr2 = [1]\n while k > len(arr):\n templast = arr.copy()\n temp2last = arr2.copy()\n arr = templast + [1] + temp2last\n arr2 = templast + [0] + temp2last\n return(str(arr[k-1]))\nn = 4\nk = 10\nprint(solve(n, k))"
},
{
"code": null,
"e": 3317,
"s": 3311,
"text": "4, 10"
},
{
"code": null,
"e": 3319,
"s": 3317,
"text": "1"
}
]
|
Object to array - JavaScript | Suppose, we have an object of key value pairs like this −
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
We are required to write a function that takes in the object and returns an array of arrays with each subarray representing one key value pair
Let’s write the code for this function −
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
const objectToArray = obj => {
const keys = Object.keys(obj);
const res = [];
for(let i = 0; i < keys.length; i++){
res.push([keys[i], obj[keys[i]]]);
};
return res;
};
console.log(objectToArray(obj));
The output in the console: −
[
[ 'name', 'Vikas' ],
[ 'age', 45 ],
[ 'occupation', 'Frontend Developer' ],
[ 'address', 'Tilak Nagar, New Delhi' ],
[ 'experience', 23 ],
[ 'salary', '98000' ]
] | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Suppose, we have an object of key value pairs like this −"
},
{
"code": null,
"e": 1280,
"s": 1120,
"text": "const obj = {\n name: \"Vikas\",\n age: 45,\n occupation: \"Frontend Developer\",\n address: \"Tilak Nagar, New Delhi\",\n experience: 23,\n salary: \"98000\"\n};"
},
{
"code": null,
"e": 1423,
"s": 1280,
"text": "We are required to write a function that takes in the object and returns an array of arrays with each subarray representing one key value pair"
},
{
"code": null,
"e": 1464,
"s": 1423,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1847,
"s": 1464,
"text": "const obj = {\n name: \"Vikas\",\n age: 45,\n occupation: \"Frontend Developer\",\n address: \"Tilak Nagar, New Delhi\",\n experience: 23,\n salary: \"98000\"\n};\nconst objectToArray = obj => {\n const keys = Object.keys(obj);\n const res = [];\n for(let i = 0; i < keys.length; i++){\n res.push([keys[i], obj[keys[i]]]);\n };\n return res;\n};\nconsole.log(objectToArray(obj));"
},
{
"code": null,
"e": 1876,
"s": 1847,
"text": "The output in the console: −"
},
{
"code": null,
"e": 2059,
"s": 1876,
"text": "[\n [ 'name', 'Vikas' ],\n [ 'age', 45 ],\n [ 'occupation', 'Frontend Developer' ],\n [ 'address', 'Tilak Nagar, New Delhi' ],\n [ 'experience', 23 ],\n [ 'salary', '98000' ]\n]"
}
]
|
Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution) - GeeksforGeeks | 26 Apr, 2021
Given an array of n unique integers where each element in the array is in the range [1, n]. The array has all distinct elements and the size of the array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers.Examples :
Input : arr[] = {1, 3, 5, 6}
Output : 2 4
Input : arr[] = {1, 2, 4}
Output : 3 5
Input : arr[] = {1, 2}
Output : 3 4
Method 1 – O(n) time complexity and O(n) Extra Space
Step 1: Take a boolean array mark that keeps track of all the elements present in the array. Step 2: Iterate from 1 to n, check for every element if it is marked as true in the boolean array, if not then simply display that element.
C++
Java
Python3
C#
Javascript
// C++ Program to find two Missing Numbers using O(n)// extra space#include <bits/stdc++.h>using namespace std; // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctvoid findTwoMissingNumbers(int arr[], int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. vector<bool> mark(n+1, false); for (int i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements cout << "Two Missing Numbers are\n"; for (int i = 1; i <= n; i++) if (! mark[i]) cout << i << " "; cout << endl;} // Driver program to test above functionint main(){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + sizeof(arr)/sizeof(arr[0]); findTwoMissingNumbers(arr, n); return 0;}
// Java Program to find two Missing Numbers using O(n)// extra spaceimport java.util.*; class GFG{ // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctstatic void findTwoMissingNumbers(int arr[], int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. boolean []mark = new boolean[n+1]; for (int i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements System.out.println("Two Missing Numbers are"); for (int i = 1; i <= n; i++) if (! mark[i]) System.out.print(i + " "); System.out.println();} // Driver codepublic static void main(String[] args){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + arr.length; findTwoMissingNumbers(arr, n);}} // This code is contributed by 29AjayKumar
# Python3 program to find two Missing Numbers using O(n)# extra space # Function to find two missing numbers in range# [1, n]. This function assumes that size of array# is n-2 and all array elements are distinctdef findTwoMissingNumbers(arr, n): # Create a boolean vector of size n+1 and # mark all present elements of arr[] in it. mark = [False for i in range(n+1)] for i in range(0,n-2,1): mark[arr[i]] = True # Print two unmarked elements print("Two Missing Numbers are") for i in range(1,n+1,1): if (mark[i] == False): print(i,end = " ") print("\n") # Driver program to test above functionif __name__ == '__main__': arr = [1, 3, 5, 6] # Range of numbers is 2 plus size of array n = 2 + len(arr) findTwoMissingNumbers(arr, n); # This code is contributed by# Surendra_Gangwar
// C# Program to find two Missing Numbers// using O(n) extra spaceusing System;using System.Collections.Generic; class GFG{ // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctstatic void findTwoMissingNumbers(int []arr, int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. Boolean []mark = new Boolean[n + 1]; for (int i = 0; i < n - 2; i++) mark[arr[i]] = true; // Print two unmarked elements Console.WriteLine("Two Missing Numbers are"); for (int i = 1; i <= n; i++) if (! mark[i]) Console.Write(i + " "); Console.WriteLine();} // Driver codepublic static void Main(String[] args){ int []arr = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + arr.Length; findTwoMissingNumbers(arr, n);}} // This code contributed by Rajput-Ji
<script> // Javascript Program to find two // Missing Numbers using O(n) extra space // Function to find two missing numbers in range // [1, n]. This function assumes that size of array // is n-2 and all array elements are distinct function findTwoMissingNumbers(arr, n) { // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. let mark = new Array(n+1); for (let i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements document.write("Two Missing Numbers are" + "</br>"); for (let i = 1; i <= n; i++) if (!mark[i]) document.write(i + " "); document.write("</br>"); } let arr = [1, 3, 5, 6]; // Range of numbers is 2 plus size of array let n = 2 + arr.length; findTwoMissingNumbers(arr, n); </script>
Output :
Two Missing Numbers are
2 4
Method 2 – O(n) time complexity and O(1) Extra Space
The idea is based on this popular solution for finding one missing number. We extend the solution so that two missing elements are printed. Let’s find out the sum of 2 missing numbers:
arrSum => Sum of all elements in the array
sum (Sum of 2 missing numbers) = (Sum of integers from 1 to n) - arrSum
= ((n)*(n+1))/2 – arrSum
avg (Average of 2 missing numbers) = sum / 2;
One of the numbers will be less than or equal to avg while the other one will be strictly greater than avg. Two numbers can never be equal since all the given numbers are distinct.
We can find the first missing number as a sum of natural numbers from 1 to avg, i.e., avg*(avg+1)/2 minus the sum of array elements smaller than avg
We can find the second missing number by subtracting the first missing number from the sum of missing numbers
Consider an example for better clarification
Input : 1 3 5 6, n = 6
Sum of missing integers = n*(n+1)/2 - (1+3+5+6) = 6.
Average of missing integers = 6/2 = 3.
Sum of array elements less than or equal to average = 1 + 3 = 4
Sum of natural numbers from 1 to avg = avg*(avg + 1)/2
= 3*4/2 = 6
First missing number = 6 - 4 = 2
Second missing number = Sum of missing integers-First missing number
Second missing number = 6-2= 4
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find 2 Missing Numbers using O(1)// extra space#include <iostream>using namespace std; // Returns the sum of the arrayint getSum(int arr[],int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctvoid findTwoMissingNumbers(int arr[],int n){ // Sum of 2 Missing Numbers int sum = (n*(n + 1)) /2 - getSum(arr, n-2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller than average (avg) // and sum of elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n-2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } cout << "Two Missing Numbers are\n"; // The first (smaller) element = (sum of natural // numbers upto avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg*(avg + 1)) / 2; int smallerElement = totalSmallerHalf - sumSmallerHalf; cout << smallerElement << " "; // The second (larger) element = (sum of both // the elements) - smaller element cout << sum - smallerElement;} // Driver program to test above functionint main(){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + sizeof(arr)/sizeof(arr[0]); findTwoMissingNumbers(arr, n); return 0;}
// Java Program to find 2 Missing// Numbers using O(1) extra spaceimport java.io.*; class GFG{ // Returns the sum of the arraystatic int getSum(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctstatic void findTwoMissingNumbers(int arr[], int n){ // Sum of 2 Missing Numbers int sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } System.out.println("Two Missing " + "Numbers are"); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg * (avg + 1)) / 2; System.out.println(totalSmallerHalf - sumSmallerHalf); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) System.out.println(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf);} // Driver Codepublic static void main (String[] args){int arr[] = {1, 3, 5, 6}; // Range of numbers is 2// plus size of arrayint n = 2 + arr.length; findTwoMissingNumbers(arr, n);}} // This code is contributed by aj_36
# Python Program to find 2 Missing# Numbers using O(1) extra space # Returns the sum of the arraydef getSum(arr,n): sum = 0; for i in range(0, n): sum += arr[i] return sum # Function to find two missing# numbers in range [1, n]. This# function assumes that size of# array is n-2 and all array# elements are distinctdef findTwoMissingNumbers(arr, n): # Sum of 2 Missing Numbers sum = ((n * (n + 1)) / 2 - getSum(arr, n - 2)); #Find average of two elements avg = (sum / 2); # Find sum of elements smaller # than average (avg) and sum # of elements greater than # average (avg) sumSmallerHalf = 0 sumGreaterHalf = 0; for i in range(0, n - 2): if (arr[i] <= avg): sumSmallerHalf += arr[i] else: sumGreaterHalf += arr[i] print("Two Missing Numbers are") # The first (smaller) element = (sum # of natural numbers upto avg) - (sum # of array elements smaller than or # equal to avg) totalSmallerHalf = (avg * (avg + 1)) / 2 print(str(totalSmallerHalf - sumSmallerHalf) + " ") # The first (smaller) element = (sum # of natural numbers from avg+1 to n) - # (sum of array elements greater than avg) print(str(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf)) # Driver Codearr = [1, 3, 5, 6] # Range of numbers is 2# plus size of arrayn = 2 + len(arr) findTwoMissingNumbers(arr, n) # This code is contributed# by Yatin Gupta
// C# Program to find 2 Missing// Numbers using O(1) extra spaceusing System; class GFG{ // Returns the sum of the arraystatic int getSum(int []arr, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctstatic void findTwoMissingNumbers(int []arr, int n){ // Sum of 2 Missing Numbers int sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } Console.WriteLine("Two Missing " + "Numbers are "); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg * (avg + 1)) / 2; Console.WriteLine(totalSmallerHalf - sumSmallerHalf); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) Console.WriteLine(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf);} // Driver Codestatic public void Main (){ int []arr = {1, 3, 5, 6}; // Range of numbers is 2 // plus size of array int n = 2 + arr.Length; findTwoMissingNumbers(arr, n);}} // This code is contributed by ajit
<?php// PHP Program to find 2 Missing// Numbers using O(1) extra space // Returns the sum of the arrayfunction getSum($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctfunction findTwoMissingNumbers($arr, $n){ // Sum of 2 Missing Numbers $sum = ($n * ($n + 1)) /2 - getSum($arr, $n - 2); // Find average of two elements $avg = ($sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) $sumSmallerHalf = 0; $sumGreaterHalf = 0; for ($i = 0; $i < $n - 2; $i++) { if ($arr[$i] <= $avg) $sumSmallerHalf += $arr[$i]; else $sumGreaterHalf += $arr[$i]; } echo "Two Missing Numbers are\n"; // The first (smaller) element = // (sum of natural numbers upto avg) - // (sum of array elements smaller // than or equal to avg) $totalSmallerHalf = ($avg * ($avg + 1)) / 2; echo ($totalSmallerHalf - $sumSmallerHalf) , " "; // The first (smaller) element = // (sum of natural numbers from avg + // 1 to n) - (sum of array elements // greater than avg) echo ((($n * ($n + 1)) / 2 - $totalSmallerHalf) - $sumGreaterHalf);} // Driver Code$arr= array (1, 3, 5, 6); // Range of numbers is// 2 plus size of array$n = 2 + sizeof($arr); findTwoMissingNumbers($arr, $n); // This code is contributed by aj_36?>
<script> // Javascript Program to find 2 Missing // Numbers using O(1) extra space // Returns the sum of the array function getSum(arr, n) { let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; return sum; } // Function to find two missing // numbers in range [1, n]. This // function assumes that size of // array is n-2 and all array // elements are distinct function findTwoMissingNumbers(arr, n) { // Sum of 2 Missing Numbers let sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements let avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) let sumSmallerHalf = 0, sumGreaterHalf = 0; for (let i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } document.write( "Two Missing " + "Numbers are " + "</br>" ); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) let totalSmallerHalf = (avg * (avg + 1)) / 2; document.write( (totalSmallerHalf - sumSmallerHalf) + " " ); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) document.write( ((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf + "</br>" ); } let arr = [1, 3, 5, 6]; // Range of numbers is 2 // plus size of array let n = 2 + arr.length; findTwoMissingNumbers(arr, n); </script>
Output :
Two Missing Numbers are
2 4
Note: There can be overflow issues in the above solution. In below set 2, another solution that is O(n) time, O(1) space, and doesn’t cause overflow issues is discussed.Find Two Missing Numbers | Set 2 (XOR based solution)This article is contributed by Chirag 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
YatinGupta
SURENDRA_GANGWAR
RaoRajkumar
29AjayKumar
Rajput-Ji
divyeshrabadiya07
mukesh07
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times | [
{
"code": null,
"e": 25045,
"s": 25017,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 25313,
"s": 25045,
"text": "Given an array of n unique integers where each element in the array is in the range [1, n]. The array has all distinct elements and the size of the array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers.Examples : "
},
{
"code": null,
"e": 25433,
"s": 25313,
"text": "Input : arr[] = {1, 3, 5, 6}\nOutput : 2 4\n\nInput : arr[] = {1, 2, 4}\nOutput : 3 5\n\nInput : arr[] = {1, 2}\nOutput : 3 4"
},
{
"code": null,
"e": 25490,
"s": 25437,
"text": "Method 1 – O(n) time complexity and O(n) Extra Space"
},
{
"code": null,
"e": 25724,
"s": 25490,
"text": "Step 1: Take a boolean array mark that keeps track of all the elements present in the array. Step 2: Iterate from 1 to n, check for every element if it is marked as true in the boolean array, if not then simply display that element. "
},
{
"code": null,
"e": 25728,
"s": 25724,
"text": "C++"
},
{
"code": null,
"e": 25733,
"s": 25728,
"text": "Java"
},
{
"code": null,
"e": 25741,
"s": 25733,
"text": "Python3"
},
{
"code": null,
"e": 25744,
"s": 25741,
"text": "C#"
},
{
"code": null,
"e": 25755,
"s": 25744,
"text": "Javascript"
},
{
"code": "// C++ Program to find two Missing Numbers using O(n)// extra space#include <bits/stdc++.h>using namespace std; // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctvoid findTwoMissingNumbers(int arr[], int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. vector<bool> mark(n+1, false); for (int i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements cout << \"Two Missing Numbers are\\n\"; for (int i = 1; i <= n; i++) if (! mark[i]) cout << i << \" \"; cout << endl;} // Driver program to test above functionint main(){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + sizeof(arr)/sizeof(arr[0]); findTwoMissingNumbers(arr, n); return 0;}",
"e": 26643,
"s": 25755,
"text": null
},
{
"code": "// Java Program to find two Missing Numbers using O(n)// extra spaceimport java.util.*; class GFG{ // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctstatic void findTwoMissingNumbers(int arr[], int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. boolean []mark = new boolean[n+1]; for (int i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements System.out.println(\"Two Missing Numbers are\"); for (int i = 1; i <= n; i++) if (! mark[i]) System.out.print(i + \" \"); System.out.println();} // Driver codepublic static void main(String[] args){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + arr.length; findTwoMissingNumbers(arr, n);}} // This code is contributed by 29AjayKumar",
"e": 27566,
"s": 26643,
"text": null
},
{
"code": "# Python3 program to find two Missing Numbers using O(n)# extra space # Function to find two missing numbers in range# [1, n]. This function assumes that size of array# is n-2 and all array elements are distinctdef findTwoMissingNumbers(arr, n): # Create a boolean vector of size n+1 and # mark all present elements of arr[] in it. mark = [False for i in range(n+1)] for i in range(0,n-2,1): mark[arr[i]] = True # Print two unmarked elements print(\"Two Missing Numbers are\") for i in range(1,n+1,1): if (mark[i] == False): print(i,end = \" \") print(\"\\n\") # Driver program to test above functionif __name__ == '__main__': arr = [1, 3, 5, 6] # Range of numbers is 2 plus size of array n = 2 + len(arr) findTwoMissingNumbers(arr, n); # This code is contributed by# Surendra_Gangwar",
"e": 28414,
"s": 27566,
"text": null
},
{
"code": "// C# Program to find two Missing Numbers// using O(n) extra spaceusing System;using System.Collections.Generic; class GFG{ // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctstatic void findTwoMissingNumbers(int []arr, int n){ // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. Boolean []mark = new Boolean[n + 1]; for (int i = 0; i < n - 2; i++) mark[arr[i]] = true; // Print two unmarked elements Console.WriteLine(\"Two Missing Numbers are\"); for (int i = 1; i <= n; i++) if (! mark[i]) Console.Write(i + \" \"); Console.WriteLine();} // Driver codepublic static void Main(String[] args){ int []arr = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + arr.Length; findTwoMissingNumbers(arr, n);}} // This code contributed by Rajput-Ji",
"e": 29360,
"s": 28414,
"text": null
},
{
"code": "<script> // Javascript Program to find two // Missing Numbers using O(n) extra space // Function to find two missing numbers in range // [1, n]. This function assumes that size of array // is n-2 and all array elements are distinct function findTwoMissingNumbers(arr, n) { // Create a boolean vector of size n+1 and // mark all present elements of arr[] in it. let mark = new Array(n+1); for (let i = 0; i < n-2; i++) mark[arr[i]] = true; // Print two unmarked elements document.write(\"Two Missing Numbers are\" + \"</br>\"); for (let i = 1; i <= n; i++) if (!mark[i]) document.write(i + \" \"); document.write(\"</br>\"); } let arr = [1, 3, 5, 6]; // Range of numbers is 2 plus size of array let n = 2 + arr.length; findTwoMissingNumbers(arr, n); </script>",
"e": 30259,
"s": 29360,
"text": null
},
{
"code": null,
"e": 30269,
"s": 30259,
"text": "Output : "
},
{
"code": null,
"e": 30297,
"s": 30269,
"text": "Two Missing Numbers are\n2 4"
},
{
"code": null,
"e": 30352,
"s": 30299,
"text": "Method 2 – O(n) time complexity and O(1) Extra Space"
},
{
"code": null,
"e": 30538,
"s": 30352,
"text": "The idea is based on this popular solution for finding one missing number. We extend the solution so that two missing elements are printed. Let’s find out the sum of 2 missing numbers: "
},
{
"code": null,
"e": 30758,
"s": 30538,
"text": "arrSum => Sum of all elements in the array\n\nsum (Sum of 2 missing numbers) = (Sum of integers from 1 to n) - arrSum\n = ((n)*(n+1))/2 – arrSum \n\navg (Average of 2 missing numbers) = sum / 2;"
},
{
"code": null,
"e": 30941,
"s": 30760,
"text": "One of the numbers will be less than or equal to avg while the other one will be strictly greater than avg. Two numbers can never be equal since all the given numbers are distinct."
},
{
"code": null,
"e": 31090,
"s": 30941,
"text": "We can find the first missing number as a sum of natural numbers from 1 to avg, i.e., avg*(avg+1)/2 minus the sum of array elements smaller than avg"
},
{
"code": null,
"e": 31200,
"s": 31090,
"text": "We can find the second missing number by subtracting the first missing number from the sum of missing numbers"
},
{
"code": null,
"e": 31247,
"s": 31200,
"text": "Consider an example for better clarification "
},
{
"code": null,
"e": 31663,
"s": 31247,
"text": "Input : 1 3 5 6, n = 6\nSum of missing integers = n*(n+1)/2 - (1+3+5+6) = 6.\nAverage of missing integers = 6/2 = 3.\nSum of array elements less than or equal to average = 1 + 3 = 4\nSum of natural numbers from 1 to avg = avg*(avg + 1)/2\n = 3*4/2 = 6\nFirst missing number = 6 - 4 = 2\nSecond missing number = Sum of missing integers-First missing number\nSecond missing number = 6-2= 4"
},
{
"code": null,
"e": 31711,
"s": 31663,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 31715,
"s": 31711,
"text": "C++"
},
{
"code": null,
"e": 31720,
"s": 31715,
"text": "Java"
},
{
"code": null,
"e": 31728,
"s": 31720,
"text": "Python3"
},
{
"code": null,
"e": 31731,
"s": 31728,
"text": "C#"
},
{
"code": null,
"e": 31735,
"s": 31731,
"text": "PHP"
},
{
"code": null,
"e": 31746,
"s": 31735,
"text": "Javascript"
},
{
"code": "// C++ Program to find 2 Missing Numbers using O(1)// extra space#include <iostream>using namespace std; // Returns the sum of the arrayint getSum(int arr[],int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing numbers in range// [1, n]. This function assumes that size of array// is n-2 and all array elements are distinctvoid findTwoMissingNumbers(int arr[],int n){ // Sum of 2 Missing Numbers int sum = (n*(n + 1)) /2 - getSum(arr, n-2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller than average (avg) // and sum of elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n-2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } cout << \"Two Missing Numbers are\\n\"; // The first (smaller) element = (sum of natural // numbers upto avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg*(avg + 1)) / 2; int smallerElement = totalSmallerHalf - sumSmallerHalf; cout << smallerElement << \" \"; // The second (larger) element = (sum of both // the elements) - smaller element cout << sum - smallerElement;} // Driver program to test above functionint main(){ int arr[] = {1, 3, 5, 6}; // Range of numbers is 2 plus size of array int n = 2 + sizeof(arr)/sizeof(arr[0]); findTwoMissingNumbers(arr, n); return 0;}",
"e": 33300,
"s": 31746,
"text": null
},
{
"code": "// Java Program to find 2 Missing// Numbers using O(1) extra spaceimport java.io.*; class GFG{ // Returns the sum of the arraystatic int getSum(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctstatic void findTwoMissingNumbers(int arr[], int n){ // Sum of 2 Missing Numbers int sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } System.out.println(\"Two Missing \" + \"Numbers are\"); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg * (avg + 1)) / 2; System.out.println(totalSmallerHalf - sumSmallerHalf); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) System.out.println(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf);} // Driver Codepublic static void main (String[] args){int arr[] = {1, 3, 5, 6}; // Range of numbers is 2// plus size of arrayint n = 2 + arr.length; findTwoMissingNumbers(arr, n);}} // This code is contributed by aj_36",
"e": 35144,
"s": 33300,
"text": null
},
{
"code": "# Python Program to find 2 Missing# Numbers using O(1) extra space # Returns the sum of the arraydef getSum(arr,n): sum = 0; for i in range(0, n): sum += arr[i] return sum # Function to find two missing# numbers in range [1, n]. This# function assumes that size of# array is n-2 and all array# elements are distinctdef findTwoMissingNumbers(arr, n): # Sum of 2 Missing Numbers sum = ((n * (n + 1)) / 2 - getSum(arr, n - 2)); #Find average of two elements avg = (sum / 2); # Find sum of elements smaller # than average (avg) and sum # of elements greater than # average (avg) sumSmallerHalf = 0 sumGreaterHalf = 0; for i in range(0, n - 2): if (arr[i] <= avg): sumSmallerHalf += arr[i] else: sumGreaterHalf += arr[i] print(\"Two Missing Numbers are\") # The first (smaller) element = (sum # of natural numbers upto avg) - (sum # of array elements smaller than or # equal to avg) totalSmallerHalf = (avg * (avg + 1)) / 2 print(str(totalSmallerHalf - sumSmallerHalf) + \" \") # The first (smaller) element = (sum # of natural numbers from avg+1 to n) - # (sum of array elements greater than avg) print(str(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf)) # Driver Codearr = [1, 3, 5, 6] # Range of numbers is 2# plus size of arrayn = 2 + len(arr) findTwoMissingNumbers(arr, n) # This code is contributed# by Yatin Gupta",
"e": 36659,
"s": 35144,
"text": null
},
{
"code": "// C# Program to find 2 Missing// Numbers using O(1) extra spaceusing System; class GFG{ // Returns the sum of the arraystatic int getSum(int []arr, int n){ int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctstatic void findTwoMissingNumbers(int []arr, int n){ // Sum of 2 Missing Numbers int sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements int avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) int sumSmallerHalf = 0, sumGreaterHalf = 0; for (int i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } Console.WriteLine(\"Two Missing \" + \"Numbers are \"); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) int totalSmallerHalf = (avg * (avg + 1)) / 2; Console.WriteLine(totalSmallerHalf - sumSmallerHalf); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) Console.WriteLine(((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf);} // Driver Codestatic public void Main (){ int []arr = {1, 3, 5, 6}; // Range of numbers is 2 // plus size of array int n = 2 + arr.Length; findTwoMissingNumbers(arr, n);}} // This code is contributed by ajit",
"e": 38495,
"s": 36659,
"text": null
},
{
"code": "<?php// PHP Program to find 2 Missing// Numbers using O(1) extra space // Returns the sum of the arrayfunction getSum($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Function to find two missing// numbers in range [1, n]. This// function assumes that size of// array is n-2 and all array// elements are distinctfunction findTwoMissingNumbers($arr, $n){ // Sum of 2 Missing Numbers $sum = ($n * ($n + 1)) /2 - getSum($arr, $n - 2); // Find average of two elements $avg = ($sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) $sumSmallerHalf = 0; $sumGreaterHalf = 0; for ($i = 0; $i < $n - 2; $i++) { if ($arr[$i] <= $avg) $sumSmallerHalf += $arr[$i]; else $sumGreaterHalf += $arr[$i]; } echo \"Two Missing Numbers are\\n\"; // The first (smaller) element = // (sum of natural numbers upto avg) - // (sum of array elements smaller // than or equal to avg) $totalSmallerHalf = ($avg * ($avg + 1)) / 2; echo ($totalSmallerHalf - $sumSmallerHalf) , \" \"; // The first (smaller) element = // (sum of natural numbers from avg + // 1 to n) - (sum of array elements // greater than avg) echo ((($n * ($n + 1)) / 2 - $totalSmallerHalf) - $sumGreaterHalf);} // Driver Code$arr= array (1, 3, 5, 6); // Range of numbers is// 2 plus size of array$n = 2 + sizeof($arr); findTwoMissingNumbers($arr, $n); // This code is contributed by aj_36?>",
"e": 40098,
"s": 38495,
"text": null
},
{
"code": "<script> // Javascript Program to find 2 Missing // Numbers using O(1) extra space // Returns the sum of the array function getSum(arr, n) { let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; return sum; } // Function to find two missing // numbers in range [1, n]. This // function assumes that size of // array is n-2 and all array // elements are distinct function findTwoMissingNumbers(arr, n) { // Sum of 2 Missing Numbers let sum = (n * (n + 1)) / 2 - getSum(arr, n - 2); // Find average of two elements let avg = (sum / 2); // Find sum of elements smaller // than average (avg) and sum of // elements greater than average (avg) let sumSmallerHalf = 0, sumGreaterHalf = 0; for (let i = 0; i < n - 2; i++) { if (arr[i] <= avg) sumSmallerHalf += arr[i]; else sumGreaterHalf += arr[i]; } document.write( \"Two Missing \" + \"Numbers are \" + \"</br>\" ); // The first (smaller) element = // (sum of natural numbers upto // avg) - (sum of array elements // smaller than or equal to avg) let totalSmallerHalf = (avg * (avg + 1)) / 2; document.write( (totalSmallerHalf - sumSmallerHalf) + \" \" ); // The first (smaller) element = // (sum of natural numbers from // avg+1 to n) - (sum of array // elements greater than avg) document.write( ((n * (n + 1)) / 2 - totalSmallerHalf) - sumGreaterHalf + \"</br>\" ); } let arr = [1, 3, 5, 6]; // Range of numbers is 2 // plus size of array let n = 2 + arr.length; findTwoMissingNumbers(arr, n); </script>",
"e": 41936,
"s": 40098,
"text": null
},
{
"code": null,
"e": 41946,
"s": 41936,
"text": "Output : "
},
{
"code": null,
"e": 41974,
"s": 41946,
"text": "Two Missing Numbers are\n2 4"
},
{
"code": null,
"e": 42619,
"s": 41974,
"text": "Note: There can be overflow issues in the above solution. In below set 2, another solution that is O(n) time, O(1) space, and doesn’t cause overflow issues is discussed.Find Two Missing Numbers | Set 2 (XOR based solution)This article is contributed by Chirag 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42625,
"s": 42619,
"text": "jit_t"
},
{
"code": null,
"e": 42636,
"s": 42625,
"text": "YatinGupta"
},
{
"code": null,
"e": 42653,
"s": 42636,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 42665,
"s": 42653,
"text": "RaoRajkumar"
},
{
"code": null,
"e": 42677,
"s": 42665,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42687,
"s": 42677,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42705,
"s": 42687,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 42714,
"s": 42705,
"text": "mukesh07"
},
{
"code": null,
"e": 42721,
"s": 42714,
"text": "Arrays"
},
{
"code": null,
"e": 42728,
"s": 42721,
"text": "Arrays"
},
{
"code": null,
"e": 42826,
"s": 42728,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42835,
"s": 42826,
"text": "Comments"
},
{
"code": null,
"e": 42848,
"s": 42835,
"text": "Old Comments"
},
{
"code": null,
"e": 42896,
"s": 42848,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 42940,
"s": 42896,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 42963,
"s": 42940,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 42995,
"s": 42963,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 43009,
"s": 42995,
"text": "Linear Search"
},
{
"code": null,
"e": 43094,
"s": 43009,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 43115,
"s": 43094,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 43160,
"s": 43115,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 43228,
"s": 43160,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
]
|
Working with Missing Data in Machine Learning | by Boyan Angelov | Towards Data Science | Missing values are representative of the messiness of real world data. There can be a multitude of reasons why they occur — ranging from human errors during data entry, incorrect sensor readings, to software bugs in the data processing pipeline.
The normal reaction is frustration. Missing data are probably the most widespread source of errors in your code, and the reason for most of the exception-handling. If you try to remove them, you might reduce the amount of data you have available dramatically — probably the worst that can happen in machine learning.
Still, often there are hidden patterns in missing data points. Those patterns can provide additional insight in the problem you’re trying to solve.
We can treat missing values in data the same way as silence in music — on the surface they might be considered negative (not contributing any information), but inside lies a lot of potential.
Note: we will be using Python and a census data set (modified for the purposes of this tutorial)
You might be surprised to find out how many methods for dealing missing data exist. This is a testament to both how important this issue is, and also that there is a lot of potential for creative problem solving.
The first thing you should do is count how many you have and try to visualize their distributions. For this step to work properly you should manually inspect the data (or at least a subset of it) to try to determine how they are designated. Possible variations are: ‘NaN’, ‘NA’, ‘None’, ‘ ’, ‘?’ and others. If you have something different than ‘NaN’ you should standardize them by using np.nan. To construct our visualizations we will use the handy missingno package.
import missingno as msnomsno.matrix(census_data)
import pandas as pdcensus_data.isnull().sum()age 325workclass 2143fnlwgt 325education 325education.num 325marital.status 325occupation 2151relationship 326race 326sex 326capital.gain 326capital.loss 326hours.per.week 326native.country 906income 326dtype: int64
Let’s start with the most simple thing you can do: removal. As mentioned before, while this is a quick solution, and might work in some cases when the proportion of missing values is relatively low (<10%), most of the time it will make you lose a ton of data. Imagine that just because of missing values in one of your features you have to drop the whole observation, even if the rest of the features are perfectly filled and informative!
import numpy as npcensus_data = census_data.replace('np.nan', 0)
The second-worst method of doing this is replacement with 0 (or -1). While this would help you run your models, it can be extremely dangerous. The reason for this is that sometimes this value can be misleading. Imagine a regression problem where negative values occur (such as predicting temperature) — well in that case this becomes an actual data point.
Now that we have those out of the way, let’s become more creative. We can split the type of missing values by their parent datatype:
A standard and often very good approach is to replace the missing values with mean, median or mode. For numerical values you should go with mean, and if there are some outliers try median (since it is much less sensitive to them).
from sklearn.preprocessing import Imputerimputer = Imputer(missing_values=np.nan, strategy='median', axis=0)census_data[['fnlwgt']] = imputer.fit_transform(census_data[['fnlwgt']])
Categorical values can be a bit trickier, so you should definitely pay attention to your model performance metrics after editing (compare before and after). The standard thing to do is to replace the missing entry with the most frequent one:
census_data['marital.status'].value_counts()Married-civ-spouse 14808Never-married 10590Divorced 4406Separated 1017Widowed 979Married-spouse-absent 413Married-AF-spouse 23Name: marital.status, dtype: int64def replace_most_common(x): if pd.isnull(x): return most_common else: return xcensus_data = census_data['marital.status'].map(replace_most_common)
The take-home message is that you should be aware of the different methods available to get more out of missing data, and more importantly start regarding it as a source of possible insight instead of annoyance!
Happy coding :)
You can theoretically impute missing values by fitting a regression model, such as linear regression or k nearest neighbors. The implementation of this is left as an example to the reader.
Here are some visualisations that are also available from the wonderful missingno package, which can help you uncover relationships, in the form of a correlation matrix or a dendrogram: | [
{
"code": null,
"e": 418,
"s": 172,
"text": "Missing values are representative of the messiness of real world data. There can be a multitude of reasons why they occur — ranging from human errors during data entry, incorrect sensor readings, to software bugs in the data processing pipeline."
},
{
"code": null,
"e": 735,
"s": 418,
"text": "The normal reaction is frustration. Missing data are probably the most widespread source of errors in your code, and the reason for most of the exception-handling. If you try to remove them, you might reduce the amount of data you have available dramatically — probably the worst that can happen in machine learning."
},
{
"code": null,
"e": 883,
"s": 735,
"text": "Still, often there are hidden patterns in missing data points. Those patterns can provide additional insight in the problem you’re trying to solve."
},
{
"code": null,
"e": 1075,
"s": 883,
"text": "We can treat missing values in data the same way as silence in music — on the surface they might be considered negative (not contributing any information), but inside lies a lot of potential."
},
{
"code": null,
"e": 1172,
"s": 1075,
"text": "Note: we will be using Python and a census data set (modified for the purposes of this tutorial)"
},
{
"code": null,
"e": 1385,
"s": 1172,
"text": "You might be surprised to find out how many methods for dealing missing data exist. This is a testament to both how important this issue is, and also that there is a lot of potential for creative problem solving."
},
{
"code": null,
"e": 1854,
"s": 1385,
"text": "The first thing you should do is count how many you have and try to visualize their distributions. For this step to work properly you should manually inspect the data (or at least a subset of it) to try to determine how they are designated. Possible variations are: ‘NaN’, ‘NA’, ‘None’, ‘ ’, ‘?’ and others. If you have something different than ‘NaN’ you should standardize them by using np.nan. To construct our visualizations we will use the handy missingno package."
},
{
"code": null,
"e": 1903,
"s": 1854,
"text": "import missingno as msnomsno.matrix(census_data)"
},
{
"code": null,
"e": 2291,
"s": 1903,
"text": "import pandas as pdcensus_data.isnull().sum()age 325workclass 2143fnlwgt 325education 325education.num 325marital.status 325occupation 2151relationship 326race 326sex 326capital.gain 326capital.loss 326hours.per.week 326native.country 906income 326dtype: int64"
},
{
"code": null,
"e": 2730,
"s": 2291,
"text": "Let’s start with the most simple thing you can do: removal. As mentioned before, while this is a quick solution, and might work in some cases when the proportion of missing values is relatively low (<10%), most of the time it will make you lose a ton of data. Imagine that just because of missing values in one of your features you have to drop the whole observation, even if the rest of the features are perfectly filled and informative!"
},
{
"code": null,
"e": 2795,
"s": 2730,
"text": "import numpy as npcensus_data = census_data.replace('np.nan', 0)"
},
{
"code": null,
"e": 3151,
"s": 2795,
"text": "The second-worst method of doing this is replacement with 0 (or -1). While this would help you run your models, it can be extremely dangerous. The reason for this is that sometimes this value can be misleading. Imagine a regression problem where negative values occur (such as predicting temperature) — well in that case this becomes an actual data point."
},
{
"code": null,
"e": 3284,
"s": 3151,
"text": "Now that we have those out of the way, let’s become more creative. We can split the type of missing values by their parent datatype:"
},
{
"code": null,
"e": 3515,
"s": 3284,
"text": "A standard and often very good approach is to replace the missing values with mean, median or mode. For numerical values you should go with mean, and if there are some outliers try median (since it is much less sensitive to them)."
},
{
"code": null,
"e": 3696,
"s": 3515,
"text": "from sklearn.preprocessing import Imputerimputer = Imputer(missing_values=np.nan, strategy='median', axis=0)census_data[['fnlwgt']] = imputer.fit_transform(census_data[['fnlwgt']])"
},
{
"code": null,
"e": 3938,
"s": 3696,
"text": "Categorical values can be a bit trickier, so you should definitely pay attention to your model performance metrics after editing (compare before and after). The standard thing to do is to replace the missing entry with the most frequent one:"
},
{
"code": null,
"e": 4393,
"s": 3938,
"text": "census_data['marital.status'].value_counts()Married-civ-spouse 14808Never-married 10590Divorced 4406Separated 1017Widowed 979Married-spouse-absent 413Married-AF-spouse 23Name: marital.status, dtype: int64def replace_most_common(x): if pd.isnull(x): return most_common else: return xcensus_data = census_data['marital.status'].map(replace_most_common)"
},
{
"code": null,
"e": 4605,
"s": 4393,
"text": "The take-home message is that you should be aware of the different methods available to get more out of missing data, and more importantly start regarding it as a source of possible insight instead of annoyance!"
},
{
"code": null,
"e": 4621,
"s": 4605,
"text": "Happy coding :)"
},
{
"code": null,
"e": 4810,
"s": 4621,
"text": "You can theoretically impute missing values by fitting a regression model, such as linear regression or k nearest neighbors. The implementation of this is left as an example to the reader."
}
]
|
Symfony - Forms | Symfony provides various in-built tags to handle HTML forms easily and securely. Symfony’s Form component performs form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create a full-fledged html form from pre-defined models. This chapter explains about Forms in detail.
Symfony framework API supports large group of field types. Let’s go through each of the field types in detail.
It is used to generate a form in Symfony framework. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
// ...
$builder = $this->createFormBuilder($studentinfo);
$builder
->add('title', TextType::class);
Here, $studentinfo is an entity of type Student. createFormBuilder is used to create a HTML form. add method is used to add input elements inside the form. title refers to student title property. TextType::class refers to html text field. Symfony provides classes for all html elements.
The TextType field represents the most basic input text field. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\TextType;
$builder->add(‘name’, TextType::class);
Here, the name is mapped with an entity.
Renders a textarea HTML element. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
$builder->add('body', TextareaType::class, array(
'attr' => array('class' => 'tinymce'),
));
The EmailType field is a text field that is rendered using the HTML5 email tag. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\EmailType;
$builder->add('token', EmailType::class, array(
'data' => 'abcdef', ));
The PasswordType field renders an input password text box. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
$bulder->add('password', PasswordType::class);
The RangeType field is a slider that is rendered using the HTML5 range tag. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\RangeType;
// ...
$builder->add('name', RangeType::class, array(
'attr' => array(
'min' => 100,
'max' => 200
)
));
The PercentType renders an input text field and specializes in handling percentage data. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\PercentType;
// ...
$builder->add('token', PercentType::class, array(
'data' => 'abcdef',
));
Renders a date format. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\DateType;
// ...
$builder->add(‘joined’, DateType::class, array(
'widget' => 'choice',
));
Here, Widget is the basic way to render a field.
It performs the following function.
choice − Renders three select inputs. The order of the selects is defined in the format option.
choice − Renders three select inputs. The order of the selects is defined in the format option.
text − Renders a three field input of type text (month, day, year).
text − Renders a three field input of type text (month, day, year).
single_text − Renders a single input of type date. The user's input is validated based on the format option.
single_text − Renders a single input of type date. The user's input is validated based on the format option.
Creates a single input checkbox. This should always be used for a field that has a boolean value. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
// ...
$builder-<add(‘sports’, CheckboxType::class, array(
'label' =< ‘Are you interested in sports?’,
'required' =< false,
));
Creates a single radio button. If the radio button is selected, the field will be set to the specified value. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\RadioType;
// ...
$builder->add('token', RadioType::class, array(
'data' => 'abcdef',
));
Note that, Radio buttons cannot be unchecked, the value only changes when another radio button with the same name gets checked.
This is a special field “group”, that creates two identical fields whose values must match. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
// ...
$builder->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'options' => array('attr' => array('class' => 'password-field')),
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
This is mostly used to check the user’s password or email.
A simple clickable button. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
// ...
$builder->add('save', ButtonType::class, array(
'attr' => array('class' => 'save'),
));
A button that resets all fields to its initial values. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\ResetType;
// ...
$builder->add('save', ResetType::class, array(
'attr' => array('class' => 'save'),
));
A multi-purpose field is used to allow the user to “choose” one or more options. It can be rendered as a select tag, radio buttons, or checkboxes. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...
$builder->add(‘gender’, ChoiceType::class, array(
'choices' => array(
‘Male’ => true,
‘Female’ => false,
),
));
A submit button is used to submit form-data. Its syntax is as follows −
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
// ...
$builder->add('save', SubmitType::class, array(
'attr' => array('class' => 'save'),
))
Form helper functions are twig functions used to create forms easily in templates.
Returns an HTML form tag that points to a valid action, route, or URL. Its syntax is as follows −
{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
Closes the HTML form tag created using form_start. Its syntax is as follows −
{{ form_end(form) }}
Returns a textarea tag, optionally wrapped with an inline rich-text JavaScript editor.
Returns an XHTML compliant input tag with type=“checkbox”. Its syntax is as follows −
echo checkbox_tag('choice[]', 1);
echo checkbox_tag('choice[]', 2);
echo checkbox_tag('choice[]', 3);
echo checkbox_tag('choice[]', 4);
Returns an XHTML compliant input tag with type = “password”. Its syntax is as follows −
echo input_password_tag('password');
echo input_password_tag('password_confirm');
Returns an XHTML compliant input tag with type = “text”. Its syntax is as follows −
echo input_tag('name');
Returns a label tag with the specified parameter.
Returns an XHTML compliant input tag with type = “radio”. Its syntax is as follows −
echo ' Yes '.radiobutton_tag(‘true’, 1);
echo ' No '.radiobutton_tag(‘false’, 0);
Returns an XHTML compliant input tag with type = “reset”. Its syntax is as follows −
echo reset_tag('Start Over');
Returns a select tag populated with all the countries in the world. Its syntax is as follows −
echo select_tag(
'url', options_for_select($url_list),
array('onChange' => 'Javascript:this.form.submit();'));
Returns an XHTML compliant input tag with type = “submit”. Its syntax is as follows −
echo submit_tag('Update Record');
In the next section, we will learn how to create a form using form fields.
Let’s create a simple Student details form using Symfony Form fields. To do this, we should adhere to the following steps −
Create a Symfony application, formsample, using the following command.
symfony new formsample
Entities are usually created under the “src/AppBundle/Entity/“ directory.
Create the file “StudentForm.php” under the “src/AppBundle/Entity/” directory. Add the following changes in the file.
<?php
namespace AppBundle\Entity;
class StudentForm {
private $studentName;
private $studentId;
public $password;
private $address;
public $joined;
public $gender;
private $email;
private $marks;
public $sports;
public function getStudentName() {
return $this->studentName;
}
public function setStudentName($studentName) {
$this->studentName = $studentName;
}
public function getStudentId() {
return $this->studentId;
}
public function setStudentId($studentid) {
$this->studentid = $studentid;
}
public function getAddress() {
return $this->address;
}
public function setAddress($address) {
$this->address = $address;
}
public function getEmail() {
return $this->email;
}
public function setEmail($email) {
$this->email = $email;
}
public function getMarks() {
return $this->marks;
}
public function setMarks($marks) {
$this->marks = $marks;
}
}
Move to the directory “src/AppBundle/Controller”, create “StudentController.php” file, and add the following code in it.
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\StudentForm;
use AppBundle\Form\FormValidationType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RangeType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
class StudentController extends Controller {
/**
* @Route("/student/new")
*/
public function newAction(Request $request) {
$stud = new StudentForm();
$form = $this->createFormBuilder($stud)
->add('studentName', TextType::class)
->add('studentId', TextType::class)
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'The password fields
must match.', 'options' => array('attr' => array('class' => 'password-field')),
'required' => true, 'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Re-enter'),
))
->add('address', TextareaType::class)
->add('joined', DateType::class, array(
'widget' => 'choice',
))
->add('gender', ChoiceType::class, array(
'choices' => array(
'Male' => true,
'Female' => false,
),
))
->add('email', EmailType::class)
->add('marks', PercentType::class)
->add('sports', CheckboxType::class, array(
'label' => 'Are you interested in sports?', 'required' => false,
))
->add('save', SubmitType::class, array('label' => 'Submit'))
->getForm();
return $this->render('student/new.html.twig', array(
'form' => $form->createView(),
));
}
}
Move to the directory “app/Resources/views/student/“, create “new.html.twig” file and add the following changes in it.
{% extends 'base.html.twig' %}
{% block stylesheets %}
<style>
#simpleform {
width:600px;
border:2px solid grey;
padding:14px;
}
#simpleform label {
font-size:14px;
float:left;
width:300px;
text-align:right;
display:block;
}
#simpleform span {
font-size:11px;
color:grey;
width:100px;
text-align:right;
display:block;
}
#simpleform input {
border:1px solid grey;
font-family:verdana;
font-size:14px;
color:light blue;
height:24px;
width:250px;
margin: 0 0 10px 10px;
}
#simpleform textarea {
border:1px solid grey;
font-family:verdana;
font-size:14px;
color:light blue;
height:120px;
width:250px;
margin: 0 0 20px 10px;
}
#simpleform select {
margin: 0 0 20px 10px;
}
#simpleform button {
clear:both;
margin-left:250px;
background: grey;
color:#FFFFFF;
border:solid 1px #666666;
font-size:16px;
}
</style>
{% endblock %}
{% block body %}
<h3>Student details:</h3>
<div id="simpleform">
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
{% endblock %}
Now request the url, “http://localhost:8000/student/new” and it produces the following result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2538,
"s": 2203,
"text": "Symfony provides various in-built tags to handle HTML forms easily and securely. Symfony’s Form component performs form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create a full-fledged html form from pre-defined models. This chapter explains about Forms in detail."
},
{
"code": null,
"e": 2649,
"s": 2538,
"text": "Symfony framework API supports large group of field types. Let’s go through each of the field types in detail."
},
{
"code": null,
"e": 2728,
"s": 2649,
"text": "It is used to generate a form in Symfony framework. Its syntax is as follows −"
},
{
"code": null,
"e": 3012,
"s": 2728,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\FormType; \n// ... \n\n$builder = $this->createFormBuilder($studentinfo); \n$builder \n ->add('title', TextType::class);\n"
},
{
"code": null,
"e": 3299,
"s": 3012,
"text": "Here, $studentinfo is an entity of type Student. createFormBuilder is used to create a HTML form. add method is used to add input elements inside the form. title refers to student title property. TextType::class refers to html text field. Symfony provides classes for all html elements."
},
{
"code": null,
"e": 3389,
"s": 3299,
"text": "The TextType field represents the most basic input text field. Its syntax is as follows −"
},
{
"code": null,
"e": 3489,
"s": 3389,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType; \n$builder->add(‘name’, TextType::class); \n"
},
{
"code": null,
"e": 3530,
"s": 3489,
"text": "Here, the name is mapped with an entity."
},
{
"code": null,
"e": 3590,
"s": 3530,
"text": "Renders a textarea HTML element. Its syntax is as follows −"
},
{
"code": null,
"e": 3751,
"s": 3590,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\TextareaType; \n$builder->add('body', TextareaType::class, array( \n 'attr' => array('class' => 'tinymce'), \n));\n"
},
{
"code": null,
"e": 3858,
"s": 3751,
"text": "The EmailType field is a text field that is rendered using the HTML5 email tag. Its syntax is as follows −"
},
{
"code": null,
"e": 3995,
"s": 3858,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType; \n$builder->add('token', EmailType::class, array( \n 'data' => 'abcdef', )); \n"
},
{
"code": null,
"e": 4081,
"s": 3995,
"text": "The PasswordType field renders an input password text box. Its syntax is as follows −"
},
{
"code": null,
"e": 4192,
"s": 4081,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\PasswordType; \n$bulder->add('password', PasswordType::class); \n"
},
{
"code": null,
"e": 4295,
"s": 4192,
"text": "The RangeType field is a slider that is rendered using the HTML5 range tag. Its syntax is as follows −"
},
{
"code": null,
"e": 4484,
"s": 4295,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\RangeType; \n// ... \n$builder->add('name', RangeType::class, array( \n 'attr' => array( \n 'min' => 100, \n 'max' => 200 \n ) \n));\n"
},
{
"code": null,
"e": 4600,
"s": 4484,
"text": "The PercentType renders an input text field and specializes in handling percentage data. Its syntax is as follows −"
},
{
"code": null,
"e": 4749,
"s": 4600,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\PercentType; \n// ... \n$builder->add('token', PercentType::class, array( \n 'data' => 'abcdef', \n));\n"
},
{
"code": null,
"e": 4799,
"s": 4749,
"text": "Renders a date format. Its syntax is as follows −"
},
{
"code": null,
"e": 4946,
"s": 4799,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\DateType; \n// ... \n$builder->add(‘joined’, DateType::class, array( \n 'widget' => 'choice', \n)); \n"
},
{
"code": null,
"e": 4995,
"s": 4946,
"text": "Here, Widget is the basic way to render a field."
},
{
"code": null,
"e": 5031,
"s": 4995,
"text": "It performs the following function."
},
{
"code": null,
"e": 5127,
"s": 5031,
"text": "choice − Renders three select inputs. The order of the selects is defined in the format option."
},
{
"code": null,
"e": 5223,
"s": 5127,
"text": "choice − Renders three select inputs. The order of the selects is defined in the format option."
},
{
"code": null,
"e": 5291,
"s": 5223,
"text": "text − Renders a three field input of type text (month, day, year)."
},
{
"code": null,
"e": 5359,
"s": 5291,
"text": "text − Renders a three field input of type text (month, day, year)."
},
{
"code": null,
"e": 5468,
"s": 5359,
"text": "single_text − Renders a single input of type date. The user's input is validated based on the format option."
},
{
"code": null,
"e": 5577,
"s": 5468,
"text": "single_text − Renders a single input of type date. The user's input is validated based on the format option."
},
{
"code": null,
"e": 5702,
"s": 5577,
"text": "Creates a single input checkbox. This should always be used for a field that has a boolean value. Its syntax is as follows −"
},
{
"code": null,
"e": 5907,
"s": 5702,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\CheckboxType; \n// ... \n$builder-<add(‘sports’, CheckboxType::class, array( \n 'label' =< ‘Are you interested in sports?’, \n 'required' =< false, \n));\n"
},
{
"code": null,
"e": 6044,
"s": 5907,
"text": "Creates a single radio button. If the radio button is selected, the field will be set to the specified value. Its syntax is as follows −"
},
{
"code": null,
"e": 6190,
"s": 6044,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\RadioType; \n// ... \n$builder->add('token', RadioType::class, array( \n 'data' => 'abcdef', \n));\n"
},
{
"code": null,
"e": 6318,
"s": 6190,
"text": "Note that, Radio buttons cannot be unchecked, the value only changes when another radio button with the same name gets checked."
},
{
"code": null,
"e": 6437,
"s": 6318,
"text": "This is a special field “group”, that creates two identical fields whose values must match. Its syntax is as follows −"
},
{
"code": null,
"e": 6934,
"s": 6437,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\RepeatedType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\PasswordType; \n\n// ... \n$builder->add('password', RepeatedType::class, array( \n 'type' => PasswordType::class, \n 'invalid_message' => 'The password fields must match.', \n 'options' => array('attr' => array('class' => 'password-field')), \n 'required' => true, \n 'first_options' => array('label' => 'Password'), \n 'second_options' => array('label' => 'Repeat Password'), \n));"
},
{
"code": null,
"e": 6993,
"s": 6934,
"text": "This is mostly used to check the user’s password or email."
},
{
"code": null,
"e": 7047,
"s": 6993,
"text": "A simple clickable button. Its syntax is as follows −"
},
{
"code": null,
"e": 7209,
"s": 7047,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\ButtonType; \n// ... \n$builder->add('save', ButtonType::class, array(\n 'attr' => array('class' => 'save'), \n));\n"
},
{
"code": null,
"e": 7291,
"s": 7209,
"text": "A button that resets all fields to its initial values. Its syntax is as follows −"
},
{
"code": null,
"e": 7452,
"s": 7291,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\ResetType; \n// ... \n$builder->add('save', ResetType::class, array( \n 'attr' => array('class' => 'save'), \n));\n"
},
{
"code": null,
"e": 7626,
"s": 7452,
"text": "A multi-purpose field is used to allow the user to “choose” one or more options. It can be rendered as a select tag, radio buttons, or checkboxes. Its syntax is as follows −"
},
{
"code": null,
"e": 7832,
"s": 7626,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\ChoiceType; \n// ... \n$builder->add(‘gender’, ChoiceType::class, array( \n 'choices' => array( \n ‘Male’ => true, \n ‘Female’ => false, \n ), \n));\n"
},
{
"code": null,
"e": 7904,
"s": 7832,
"text": "A submit button is used to submit form-data. Its syntax is as follows −"
},
{
"code": null,
"e": 8066,
"s": 7904,
"text": "use Symfony\\Component\\Form\\Extension\\Core\\Type\\SubmitType; \n// ... \n$builder->add('save', SubmitType::class, array( \n 'attr' => array('class' => 'save'), \n))\n"
},
{
"code": null,
"e": 8149,
"s": 8066,
"text": "Form helper functions are twig functions used to create forms easily in templates."
},
{
"code": null,
"e": 8247,
"s": 8149,
"text": "Returns an HTML form tag that points to a valid action, route, or URL. Its syntax is as follows −"
},
{
"code": null,
"e": 8310,
"s": 8247,
"text": "{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }} \n"
},
{
"code": null,
"e": 8388,
"s": 8310,
"text": "Closes the HTML form tag created using form_start. Its syntax is as follows −"
},
{
"code": null,
"e": 8411,
"s": 8388,
"text": "{{ form_end(form) }} \n"
},
{
"code": null,
"e": 8498,
"s": 8411,
"text": "Returns a textarea tag, optionally wrapped with an inline rich-text JavaScript editor."
},
{
"code": null,
"e": 8584,
"s": 8498,
"text": "Returns an XHTML compliant input tag with type=“checkbox”. Its syntax is as follows −"
},
{
"code": null,
"e": 8728,
"s": 8584,
"text": "echo checkbox_tag('choice[]', 1); \necho checkbox_tag('choice[]', 2); \necho checkbox_tag('choice[]', 3); \necho checkbox_tag('choice[]', 4); \n"
},
{
"code": null,
"e": 8816,
"s": 8728,
"text": "Returns an XHTML compliant input tag with type = “password”. Its syntax is as follows −"
},
{
"code": null,
"e": 8901,
"s": 8816,
"text": "echo input_password_tag('password'); \necho input_password_tag('password_confirm');\n"
},
{
"code": null,
"e": 8985,
"s": 8901,
"text": "Returns an XHTML compliant input tag with type = “text”. Its syntax is as follows −"
},
{
"code": null,
"e": 9011,
"s": 8985,
"text": "echo input_tag('name'); \n"
},
{
"code": null,
"e": 9061,
"s": 9011,
"text": "Returns a label tag with the specified parameter."
},
{
"code": null,
"e": 9146,
"s": 9061,
"text": "Returns an XHTML compliant input tag with type = “radio”. Its syntax is as follows −"
},
{
"code": null,
"e": 9232,
"s": 9146,
"text": "echo ' Yes '.radiobutton_tag(‘true’, 1); \necho ' No '.radiobutton_tag(‘false’, 0); \n"
},
{
"code": null,
"e": 9317,
"s": 9232,
"text": "Returns an XHTML compliant input tag with type = “reset”. Its syntax is as follows −"
},
{
"code": null,
"e": 9349,
"s": 9317,
"text": "echo reset_tag('Start Over'); \n"
},
{
"code": null,
"e": 9444,
"s": 9349,
"text": "Returns a select tag populated with all the countries in the world. Its syntax is as follows −"
},
{
"code": null,
"e": 9564,
"s": 9444,
"text": "echo select_tag(\n 'url', options_for_select($url_list), \n array('onChange' => 'Javascript:this.form.submit();')); \n"
},
{
"code": null,
"e": 9650,
"s": 9564,
"text": "Returns an XHTML compliant input tag with type = “submit”. Its syntax is as follows −"
},
{
"code": null,
"e": 9687,
"s": 9650,
"text": "echo submit_tag('Update Record'); \n"
},
{
"code": null,
"e": 9762,
"s": 9687,
"text": "In the next section, we will learn how to create a form using form fields."
},
{
"code": null,
"e": 9886,
"s": 9762,
"text": "Let’s create a simple Student details form using Symfony Form fields. To do this, we should adhere to the following steps −"
},
{
"code": null,
"e": 9957,
"s": 9886,
"text": "Create a Symfony application, formsample, using the following command."
},
{
"code": null,
"e": 9981,
"s": 9957,
"text": "symfony new formsample\n"
},
{
"code": null,
"e": 10055,
"s": 9981,
"text": "Entities are usually created under the “src/AppBundle/Entity/“ directory."
},
{
"code": null,
"e": 10173,
"s": 10055,
"text": "Create the file “StudentForm.php” under the “src/AppBundle/Entity/” directory. Add the following changes in the file."
},
{
"code": null,
"e": 11230,
"s": 10173,
"text": "<?php \nnamespace AppBundle\\Entity; \n\nclass StudentForm { \n private $studentName; \n private $studentId; \n public $password; \n private $address; \n public $joined; \n public $gender; \n private $email; \n private $marks; \n public $sports; \n \n public function getStudentName() { \n return $this->studentName; \n } \n public function setStudentName($studentName) { \n $this->studentName = $studentName; \n } \n public function getStudentId() { \n return $this->studentId; \n } \n public function setStudentId($studentid) { \n $this->studentid = $studentid; \n }\n public function getAddress() { \n return $this->address; \n } \n public function setAddress($address) { \n $this->address = $address; \n } \n public function getEmail() { \n return $this->email; \n } \n public function setEmail($email) { \n $this->email = $email; \n } \n public function getMarks() { \n return $this->marks; \n } \n public function setMarks($marks) { \n $this->marks = $marks; \n } \n} "
},
{
"code": null,
"e": 11351,
"s": 11230,
"text": "Move to the directory “src/AppBundle/Controller”, create “StudentController.php” file, and add the following code in it."
},
{
"code": null,
"e": 13987,
"s": 11351,
"text": "<?php \nnamespace AppBundle\\Controller; \n\nuse AppBundle\\Entity\\StudentForm; \nuse AppBundle\\Form\\FormValidationType; \n\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; \nuse Symfony\\Component\\HttpFoundation\\Request; \nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route; \n\nuse Symfony\\Component\\HttpFoundation\\Response; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\DateType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\SubmitType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\ChoiceType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\PasswordType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\RangeType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\CheckboxType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\ButtonType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\TextareaType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\PercentType; \nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\RepeatedType; \n\nclass StudentController extends Controller { \n /** \n * @Route(\"/student/new\") \n */ \n public function newAction(Request $request) { \n $stud = new StudentForm(); \n $form = $this->createFormBuilder($stud) \n ->add('studentName', TextType::class)\n ->add('studentId', TextType::class) \n ->add('password', RepeatedType::class, array( \n 'type' => PasswordType::class, \n 'invalid_message' => 'The password fields \n must match.', 'options' => array('attr' => array('class' => 'password-field')), \n 'required' => true, 'first_options' => array('label' => 'Password'), \n 'second_options' => array('label' => 'Re-enter'), \n )) \n \n ->add('address', TextareaType::class) \n ->add('joined', DateType::class, array( \n 'widget' => 'choice', \n )) \n \n ->add('gender', ChoiceType::class, array( \n 'choices' => array( \n 'Male' => true, \n 'Female' => false, \n ), \n )) \n \n ->add('email', EmailType::class) \n ->add('marks', PercentType::class) \n ->add('sports', CheckboxType::class, array( \n 'label' => 'Are you interested in sports?', 'required' => false, \n )) \n \n ->add('save', SubmitType::class, array('label' => 'Submit')) \n ->getForm(); \n return $this->render('student/new.html.twig', array( \n 'form' => $form->createView(), \n )); \n } \n} "
},
{
"code": null,
"e": 14106,
"s": 13987,
"text": "Move to the directory “app/Resources/views/student/“, create “new.html.twig” file and add the following changes in it."
},
{
"code": null,
"e": 15430,
"s": 14106,
"text": "{% extends 'base.html.twig' %} \n{% block stylesheets %} \n<style> \n #simpleform { \n width:600px; \n border:2px solid grey; \n padding:14px; \n } \n #simpleform label { \n font-size:14px; \n float:left; \n width:300px; \n text-align:right; \n display:block; \n } \n #simpleform span { \n font-size:11px; \n color:grey; \n width:100px; \n text-align:right; \n display:block; \n } \n #simpleform input { \n border:1px solid grey; \n font-family:verdana; \n font-size:14px;\n color:light blue; \n height:24px; \n width:250px; \n margin: 0 0 10px 10px; \n } \n #simpleform textarea { \n border:1px solid grey; \n font-family:verdana; \n font-size:14px; \n color:light blue; \n height:120px; \n width:250px; \n margin: 0 0 20px 10px; \n } \n #simpleform select { \n margin: 0 0 20px 10px; \n } \n #simpleform button { \n clear:both; \n margin-left:250px; \n background: grey; \n color:#FFFFFF; \n border:solid 1px #666666; \n font-size:16px; \n } \n</style> \n\n{% endblock %} \n {% block body %} \n <h3>Student details:</h3> \n <div id=\"simpleform\"> \n {{ form_start(form) }} \n {{ form_widget(form) }} \n {{ form_end(form) }} \n </div> \n{% endblock %} "
},
{
"code": null,
"e": 15525,
"s": 15430,
"text": "Now request the url, “http://localhost:8000/student/new” and it produces the following result."
},
{
"code": null,
"e": 15532,
"s": 15525,
"text": " Print"
},
{
"code": null,
"e": 15543,
"s": 15532,
"text": " Add Notes"
}
]
|
How null is converted to String in JavaScript? | Use the String() method in JavaScript to convert to String.
You can try to run the following code to learn how to convert null to String in JavaScript.
Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Convert null to String</p>
<script>
var myVal = null;
document.write("String: " + String(myVal));
</script>
</body>
</html> | [
{
"code": null,
"e": 1122,
"s": 1062,
"text": "Use the String() method in JavaScript to convert to String."
},
{
"code": null,
"e": 1214,
"s": 1122,
"text": "You can try to run the following code to learn how to convert null to String in JavaScript."
},
{
"code": null,
"e": 1224,
"s": 1214,
"text": "Live Demo"
},
{
"code": null,
"e": 1423,
"s": 1224,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Convert null to String</p>\n <script>\n var myVal = null;\n document.write(\"String: \" + String(myVal));\n </script>\n </body>\n</html>"
}
]
|
How to create table header in HTML? | To create table header in HTML, use the <th>...</th> tag. A table header tag is surrounded by the table row <tr>...</tr>. The <tr> tag is surrounded by the <table> tag. A table consist of a rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. Use the style attribute to add CSS properties for adding a border to the table.
A table row is defined by the <tr> tag. To create table header, use the <th> tag. Just keep in mind that you can only have a single heading in a table.
You can try the following code to create table header in HTML. We’re also using the <style> tag to style the table borders
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Database</h1>
<table>
<tr>
<th>Database</th>
<th>Release Year</th>
</tr>
<tr>
<td>MySQL</td>
<td>1995</td>
</tr>
</table>
</body>
</html> | [
{
"code": null,
"e": 1416,
"s": 1062,
"text": "To create table header in HTML, use the <th>...</th> tag. A table header tag is surrounded by the table row <tr>...</tr>. The <tr> tag is surrounded by the <table> tag. A table consist of a rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. Use the style attribute to add CSS properties for adding a border to the table."
},
{
"code": null,
"e": 1568,
"s": 1416,
"text": "A table row is defined by the <tr> tag. To create table header, use the <th> tag. Just keep in mind that you can only have a single heading in a table."
},
{
"code": null,
"e": 1691,
"s": 1568,
"text": "You can try the following code to create table header in HTML. We’re also using the <style> tag to style the table borders"
},
{
"code": null,
"e": 2095,
"s": 1691,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n }\n </style>\n </head>\n\n <body>\n <h1>Database</h1>\n <table>\n <tr>\n <th>Database</th>\n <th>Release Year</th>\n </tr>\n <tr>\n <td>MySQL</td>\n <td>1995</td>\n </tr>\n </table>\n </body>\n</html>"
}
]
|
A Practical Guide for Exploratory Data Analysis: Movies on Streaming Platforms | by Soner Yıldırım | Towards Data Science | Exploring movies on Netflix, Hulu, Prime Video, and Disney+.
We live in the era of big data. We can collect lots of data which allows to infer meaningful results and make informed business decisions. To get the most out of data, a robust and thorough data analysis process is needed. In this post, we will try to explore a dataset about the movies on streaming platforms. The data is available here on Kaggle.
We can directly download Kaggle datasets into a Google Colab environment. Here is a step-by-step explanation on how to do it:
towardsdatascience.com
Let’s start with downloading the dataset and read it into a pandas dataframe.
import pandas as pdimport numpy as np!kaggle datasets download -d ruchi798/movies-on-netflix-prime-video-hulu-and-disneydf = pd.read_csv("/content/movies-on-netflix-prime-video-hulu-and-disney.zip")df.drop(["Unnamed: 0", "ID", "Type"], axis=1, inplace=True)df.head()
“Unnamed: 0” and “ID” columns are redundant as they do not provide any information about the movies so we drop them. “Type” column indicates whether the title is a movie or TV show. We drop them because all of the rows contain data on movies.
We have data on movies and information about their availability on streaming platforms. Movie ratings from IMDb and Rotten Tomatoes are also provided.
It is a good practice to handle missing values first.
df.shape(16744, 14)
Dataset includes more than 16k rows and 14 columns. Let’s see how many missing values each column contains.
df.isna().sum()
Most of the values in “Age” and “Rotten Tomatoes” column are missing. Some other columns also have missing values. There is a great python library to explore missing values in a dataset which is missingno. We can plot a missing value matrix to have an idea of the distribution of missing values in the dataset.
import missingno as msno%matplotlib inlinemsno.matrix(df)
White lines indicate missing values. Missing values dominate “Age” and “Rotten Tomatoes” columns as expected. The interesting schema is that the missing values in the other columns are mostly matching. Rows either have no missing values or have missing values in multiple columns. Also the number of rows with missing values are much less than number of rows with no missing value. Thus, we can drop the rows that contain any missing value. Please note that we cannot always drop missing values. In some cases, we cannot just afford to drop them. Instead, we need to find a way to fill the missing values. It highly depends on the task we are working on.
df.drop(['Age', 'Rotten Tomatoes'], axis=1, inplace=True)df.dropna(axis=0, how='any', inplace=True)df.isna().sum().sum()0df.shape(15233, 12)
We have lost about 9% of the rows. The dataset does not have any missing values now.
Let’s first see the language distribution within movies. We will use a recently published pandas utility library called sidetable. Sidetable creates a frequency table based on selected columns. It is kind of an improved version of value_counts function. If you’d like to learn more about sidetable, you can visit the following post:
towardsdatascience.com
!pip install sidetableimport sidetabledf.stb.freq(['Language'], thresh=.8)
English movies lead by far. There are 10300 English movies which constitutes 67% of the entire dataset. 9 languages dominate almost 80% of all the movies.
IMDb rating is a very important criterion for a movie as many people select a movie to watch based on IMDb ratings. Let’s see the distribution of IMDb ratings.
df['IMDb'].describe()
Another way is to plot the distribution.
plt.figure(figsize=(10,6))plt.title("Distribution of IMDb Ratings", fontsize=15)sns.distplot(df['IMDb'])
Most of the movies fall between 5 and 8 around the mean rating of 5.89. We also see a smaller number of extreme values on both high and low sides.
If you like watching movies, you probably have a favourite director. We can check the average IMDb rating of directors.
df[['IMDb','Directors']].groupby('Directors').agg(['mean','count']).sort_values(by=('IMDb','mean'), ascending=False)[:10]
There are the top 10 directors in terms of IMDb ratings. However, all of them have only one movie which I think is not enough for a true evaluation. Let’s change it to rank directors who have at least 5 movies.
directors = df[['IMDb','Directors']].groupby('Directors').agg(['mean','count'])directors[directors[('IMDb', 'count')] > 5].sort_values(by=('IMDb','mean'), ascending=False)[:10]
The platforms contained in the dataset are Netflix, Hulu, Prime Video, and Disney+. Some movies are only in one of these platforms whereas some are available on multiple platforms. Let’s check how many movies each platform has and also the average IMDb ratings of platforms.
df[['IMDb','Netflix']].groupby(['Netflix']).agg(['mean','count'])
Netflix has 3152 movies and the average IMDb rating is 5.8. Instead of checking one-by-one, we can create a for loop and save the results into a dictionary and then create a dataframe from that dictionary.
streams = ['Netflix', 'Hulu', 'Prime Video', 'Disney+']dict_a = {}for stream in streams: a = df[['IMDb', stream]].groupby([stream]).agg(['mean', 'count']).iloc[1,:].values dict_a[stream] = a df_stream = pd.DataFrame(dict_a, index=['Avg_IMDb','Number of Moviews'])df_stream
We take the second row of what groupby function returns because second row contains the data on movies available (1) on that platform. Then, the row is saved in a dictionary with a key which is the name of the platform. After the dictionary is complete, it is converted to a dataframe.
Prime Video has most movies by far and the lowest average IMDb rating. I think this indicates Prime Video is not very selective about the content. Disney+ has the highest average IMDb rating, followed closely by Netflix.
The advancement in technology and streaming platforms have made it possible for us to watch movies from all over the world. Due to the different taste and preferences in different countries, streaming platforms usually change their contents based on the country. Let’s see which countries have the richest content.
df.stb.freq(['Country'], thresh=.75)
United States leads by far with more than 50%.
Although there are some exceptions, the length of movies are usually between 1.5 and 2 hours. Let’s see the distribution of runtime.
plt.figure(figsize=(10,6))plt.title("Movie Length Distribution", fontsize=15)sns.distplot(df.Runtime)
We see a normal distribution with a mean around 90 minutes.
df.Runtime.describe()
The average is 94 minutes. We also see a movie that is 1 minute long which must be a mistake. Let’s see what are these movies.
df.query('Runtime > 300 or Runtime < 2')
Custer’s Last Stand is really 328 minutes long but the other is, of course, not 1-minute.
I wonder if there is any correlation between length of the movie and IMDb rating. We can use corr function of pandas to check.
df[['IMDb','Runtime']].corr()
There is not a significant correlation between IMDb rating and runtime.
We have tried approach the dataset from a few different perspectives but there is no limit to the exploratory data analysis process. We can approach the dataframe from a specific point of view depending on our needs. However, the techniques and operations are usually the same. So, it is better to practice with different kind of datasets.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 232,
"s": 171,
"text": "Exploring movies on Netflix, Hulu, Prime Video, and Disney+."
},
{
"code": null,
"e": 581,
"s": 232,
"text": "We live in the era of big data. We can collect lots of data which allows to infer meaningful results and make informed business decisions. To get the most out of data, a robust and thorough data analysis process is needed. In this post, we will try to explore a dataset about the movies on streaming platforms. The data is available here on Kaggle."
},
{
"code": null,
"e": 707,
"s": 581,
"text": "We can directly download Kaggle datasets into a Google Colab environment. Here is a step-by-step explanation on how to do it:"
},
{
"code": null,
"e": 730,
"s": 707,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 808,
"s": 730,
"text": "Let’s start with downloading the dataset and read it into a pandas dataframe."
},
{
"code": null,
"e": 1075,
"s": 808,
"text": "import pandas as pdimport numpy as np!kaggle datasets download -d ruchi798/movies-on-netflix-prime-video-hulu-and-disneydf = pd.read_csv(\"/content/movies-on-netflix-prime-video-hulu-and-disney.zip\")df.drop([\"Unnamed: 0\", \"ID\", \"Type\"], axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 1318,
"s": 1075,
"text": "“Unnamed: 0” and “ID” columns are redundant as they do not provide any information about the movies so we drop them. “Type” column indicates whether the title is a movie or TV show. We drop them because all of the rows contain data on movies."
},
{
"code": null,
"e": 1469,
"s": 1318,
"text": "We have data on movies and information about their availability on streaming platforms. Movie ratings from IMDb and Rotten Tomatoes are also provided."
},
{
"code": null,
"e": 1523,
"s": 1469,
"text": "It is a good practice to handle missing values first."
},
{
"code": null,
"e": 1543,
"s": 1523,
"text": "df.shape(16744, 14)"
},
{
"code": null,
"e": 1651,
"s": 1543,
"text": "Dataset includes more than 16k rows and 14 columns. Let’s see how many missing values each column contains."
},
{
"code": null,
"e": 1667,
"s": 1651,
"text": "df.isna().sum()"
},
{
"code": null,
"e": 1978,
"s": 1667,
"text": "Most of the values in “Age” and “Rotten Tomatoes” column are missing. Some other columns also have missing values. There is a great python library to explore missing values in a dataset which is missingno. We can plot a missing value matrix to have an idea of the distribution of missing values in the dataset."
},
{
"code": null,
"e": 2036,
"s": 1978,
"text": "import missingno as msno%matplotlib inlinemsno.matrix(df)"
},
{
"code": null,
"e": 2691,
"s": 2036,
"text": "White lines indicate missing values. Missing values dominate “Age” and “Rotten Tomatoes” columns as expected. The interesting schema is that the missing values in the other columns are mostly matching. Rows either have no missing values or have missing values in multiple columns. Also the number of rows with missing values are much less than number of rows with no missing value. Thus, we can drop the rows that contain any missing value. Please note that we cannot always drop missing values. In some cases, we cannot just afford to drop them. Instead, we need to find a way to fill the missing values. It highly depends on the task we are working on."
},
{
"code": null,
"e": 2832,
"s": 2691,
"text": "df.drop(['Age', 'Rotten Tomatoes'], axis=1, inplace=True)df.dropna(axis=0, how='any', inplace=True)df.isna().sum().sum()0df.shape(15233, 12)"
},
{
"code": null,
"e": 2917,
"s": 2832,
"text": "We have lost about 9% of the rows. The dataset does not have any missing values now."
},
{
"code": null,
"e": 3250,
"s": 2917,
"text": "Let’s first see the language distribution within movies. We will use a recently published pandas utility library called sidetable. Sidetable creates a frequency table based on selected columns. It is kind of an improved version of value_counts function. If you’d like to learn more about sidetable, you can visit the following post:"
},
{
"code": null,
"e": 3273,
"s": 3250,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3348,
"s": 3273,
"text": "!pip install sidetableimport sidetabledf.stb.freq(['Language'], thresh=.8)"
},
{
"code": null,
"e": 3503,
"s": 3348,
"text": "English movies lead by far. There are 10300 English movies which constitutes 67% of the entire dataset. 9 languages dominate almost 80% of all the movies."
},
{
"code": null,
"e": 3663,
"s": 3503,
"text": "IMDb rating is a very important criterion for a movie as many people select a movie to watch based on IMDb ratings. Let’s see the distribution of IMDb ratings."
},
{
"code": null,
"e": 3685,
"s": 3663,
"text": "df['IMDb'].describe()"
},
{
"code": null,
"e": 3726,
"s": 3685,
"text": "Another way is to plot the distribution."
},
{
"code": null,
"e": 3831,
"s": 3726,
"text": "plt.figure(figsize=(10,6))plt.title(\"Distribution of IMDb Ratings\", fontsize=15)sns.distplot(df['IMDb'])"
},
{
"code": null,
"e": 3978,
"s": 3831,
"text": "Most of the movies fall between 5 and 8 around the mean rating of 5.89. We also see a smaller number of extreme values on both high and low sides."
},
{
"code": null,
"e": 4098,
"s": 3978,
"text": "If you like watching movies, you probably have a favourite director. We can check the average IMDb rating of directors."
},
{
"code": null,
"e": 4220,
"s": 4098,
"text": "df[['IMDb','Directors']].groupby('Directors').agg(['mean','count']).sort_values(by=('IMDb','mean'), ascending=False)[:10]"
},
{
"code": null,
"e": 4431,
"s": 4220,
"text": "There are the top 10 directors in terms of IMDb ratings. However, all of them have only one movie which I think is not enough for a true evaluation. Let’s change it to rank directors who have at least 5 movies."
},
{
"code": null,
"e": 4608,
"s": 4431,
"text": "directors = df[['IMDb','Directors']].groupby('Directors').agg(['mean','count'])directors[directors[('IMDb', 'count')] > 5].sort_values(by=('IMDb','mean'), ascending=False)[:10]"
},
{
"code": null,
"e": 4883,
"s": 4608,
"text": "The platforms contained in the dataset are Netflix, Hulu, Prime Video, and Disney+. Some movies are only in one of these platforms whereas some are available on multiple platforms. Let’s check how many movies each platform has and also the average IMDb ratings of platforms."
},
{
"code": null,
"e": 4949,
"s": 4883,
"text": "df[['IMDb','Netflix']].groupby(['Netflix']).agg(['mean','count'])"
},
{
"code": null,
"e": 5155,
"s": 4949,
"text": "Netflix has 3152 movies and the average IMDb rating is 5.8. Instead of checking one-by-one, we can create a for loop and save the results into a dictionary and then create a dataframe from that dictionary."
},
{
"code": null,
"e": 5460,
"s": 5155,
"text": "streams = ['Netflix', 'Hulu', 'Prime Video', 'Disney+']dict_a = {}for stream in streams: a = df[['IMDb', stream]].groupby([stream]).agg(['mean', 'count']).iloc[1,:].values dict_a[stream] = a df_stream = pd.DataFrame(dict_a, index=['Avg_IMDb','Number of Moviews'])df_stream"
},
{
"code": null,
"e": 5746,
"s": 5460,
"text": "We take the second row of what groupby function returns because second row contains the data on movies available (1) on that platform. Then, the row is saved in a dictionary with a key which is the name of the platform. After the dictionary is complete, it is converted to a dataframe."
},
{
"code": null,
"e": 5967,
"s": 5746,
"text": "Prime Video has most movies by far and the lowest average IMDb rating. I think this indicates Prime Video is not very selective about the content. Disney+ has the highest average IMDb rating, followed closely by Netflix."
},
{
"code": null,
"e": 6282,
"s": 5967,
"text": "The advancement in technology and streaming platforms have made it possible for us to watch movies from all over the world. Due to the different taste and preferences in different countries, streaming platforms usually change their contents based on the country. Let’s see which countries have the richest content."
},
{
"code": null,
"e": 6319,
"s": 6282,
"text": "df.stb.freq(['Country'], thresh=.75)"
},
{
"code": null,
"e": 6366,
"s": 6319,
"text": "United States leads by far with more than 50%."
},
{
"code": null,
"e": 6499,
"s": 6366,
"text": "Although there are some exceptions, the length of movies are usually between 1.5 and 2 hours. Let’s see the distribution of runtime."
},
{
"code": null,
"e": 6601,
"s": 6499,
"text": "plt.figure(figsize=(10,6))plt.title(\"Movie Length Distribution\", fontsize=15)sns.distplot(df.Runtime)"
},
{
"code": null,
"e": 6661,
"s": 6601,
"text": "We see a normal distribution with a mean around 90 minutes."
},
{
"code": null,
"e": 6683,
"s": 6661,
"text": "df.Runtime.describe()"
},
{
"code": null,
"e": 6810,
"s": 6683,
"text": "The average is 94 minutes. We also see a movie that is 1 minute long which must be a mistake. Let’s see what are these movies."
},
{
"code": null,
"e": 6851,
"s": 6810,
"text": "df.query('Runtime > 300 or Runtime < 2')"
},
{
"code": null,
"e": 6941,
"s": 6851,
"text": "Custer’s Last Stand is really 328 minutes long but the other is, of course, not 1-minute."
},
{
"code": null,
"e": 7068,
"s": 6941,
"text": "I wonder if there is any correlation between length of the movie and IMDb rating. We can use corr function of pandas to check."
},
{
"code": null,
"e": 7098,
"s": 7068,
"text": "df[['IMDb','Runtime']].corr()"
},
{
"code": null,
"e": 7170,
"s": 7098,
"text": "There is not a significant correlation between IMDb rating and runtime."
},
{
"code": null,
"e": 7510,
"s": 7170,
"text": "We have tried approach the dataset from a few different perspectives but there is no limit to the exploratory data analysis process. We can approach the dataframe from a specific point of view depending on our needs. However, the techniques and operations are usually the same. So, it is better to practice with different kind of datasets."
}
]
|
Assert Statements in Dart - GeeksforGeeks | 20 Jul, 2020
As a programmer, it is very necessary to make an errorless code is very necessary and to find the error is very difficult in a big program. Dart provides the programmer with assert statements to check for the error. The assert statement is a useful tool to debug the code and it uses boolean condition for testing. If the boolean expression in assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error.
Syntax: assert(condition);
It must be noted that if you want to use assert then you have to enable it while execution as it can only be used in the development mode and not in productive mode. If it is not enabled then it will be simply be ignored while execution.
Enable the assert while executing a dart file via cmd as:
dart --enable-asserts file_name.dart
Example 1: Using assert in a dart program.
Dart
void main(){ String geek = "Geeks For Geeks"; assert(geek != "Geeks For Geeks"); print("You Can See This Line Geek as a Output");}
Output when Asserts are enabled:
Unhandled exception:
'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek != "Geeks For Geeks"': is not true.
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
Output through cmd:
Output when Asserts are not enabled:
You Can See This Line Geek as a Output
Output through cmd:
Apart from that, you can also send a message for the case if the assert returns false as:
assert(condition, "message");
It is very useful when you are trying to debug various errors and want to know which assert returned the error in the code.
Example 2: Using assert to give the message in a dart program.
Dart
void main(){ String geek = "Geeks For Geeks"; assert(geek != "Geeks For Geeks", "Strings are equal So this message is been displayed!!"); print("You Can See This Line Geek as a Output if assert returns true");}
Output:
C:\Users\msaur\Desktop>dart --enable-asserts GeeksForGeeks.dart
Unhandled exception:
'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek !=
"Geeks For Geeks"': Strings are equal So this message is been displayed!!
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
Output through cmd:
Dart-Exception-Handling
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Row and Column Widgets
Dart Tutorial
Flutter - BoxShadow Widget
Flutter - Flexible Widget
ListView Class in Flutter
Container class in Flutter
Flutter - Stack Widget | [
{
"code": null,
"e": 24004,
"s": 23976,
"text": "\n20 Jul, 2020"
},
{
"code": null,
"e": 24474,
"s": 24004,
"text": "As a programmer, it is very necessary to make an errorless code is very necessary and to find the error is very difficult in a big program. Dart provides the programmer with assert statements to check for the error. The assert statement is a useful tool to debug the code and it uses boolean condition for testing. If the boolean expression in assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error."
},
{
"code": null,
"e": 24502,
"s": 24474,
"text": "Syntax: assert(condition);\n"
},
{
"code": null,
"e": 24740,
"s": 24502,
"text": "It must be noted that if you want to use assert then you have to enable it while execution as it can only be used in the development mode and not in productive mode. If it is not enabled then it will be simply be ignored while execution."
},
{
"code": null,
"e": 24798,
"s": 24740,
"text": "Enable the assert while executing a dart file via cmd as:"
},
{
"code": null,
"e": 24836,
"s": 24798,
"text": "dart --enable-asserts file_name.dart\n"
},
{
"code": null,
"e": 24879,
"s": 24836,
"text": "Example 1: Using assert in a dart program."
},
{
"code": null,
"e": 24886,
"s": 24881,
"text": "Dart"
},
{
"code": "void main(){ String geek = \"Geeks For Geeks\"; assert(geek != \"Geeks For Geeks\"); print(\"You Can See This Line Geek as a Output\");}",
"e": 25020,
"s": 24886,
"text": null
},
{
"code": null,
"e": 25055,
"s": 25022,
"text": "Output when Asserts are enabled:"
},
{
"code": null,
"e": 25608,
"s": 25055,
"text": "Unhandled exception:\n'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek != \"Geeks For Geeks\"': is not true.\n#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)\n#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)\n#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)\n#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)\n#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)\n\n"
},
{
"code": null,
"e": 25628,
"s": 25608,
"text": "Output through cmd:"
},
{
"code": null,
"e": 25665,
"s": 25628,
"text": "Output when Asserts are not enabled:"
},
{
"code": null,
"e": 25705,
"s": 25665,
"text": "You Can See This Line Geek as a Output\n"
},
{
"code": null,
"e": 25725,
"s": 25705,
"text": "Output through cmd:"
},
{
"code": null,
"e": 25815,
"s": 25725,
"text": "Apart from that, you can also send a message for the case if the assert returns false as:"
},
{
"code": null,
"e": 25846,
"s": 25815,
"text": "assert(condition, \"message\");\n"
},
{
"code": null,
"e": 25970,
"s": 25846,
"text": "It is very useful when you are trying to debug various errors and want to know which assert returned the error in the code."
},
{
"code": null,
"e": 26033,
"s": 25970,
"text": "Example 2: Using assert to give the message in a dart program."
},
{
"code": null,
"e": 26038,
"s": 26033,
"text": "Dart"
},
{
"code": "void main(){ String geek = \"Geeks For Geeks\"; assert(geek != \"Geeks For Geeks\", \"Strings are equal So this message is been displayed!!\"); print(\"You Can See This Line Geek as a Output if assert returns true\");}",
"e": 26252,
"s": 26038,
"text": null
},
{
"code": null,
"e": 26262,
"s": 26254,
"text": "Output:"
},
{
"code": null,
"e": 26921,
"s": 26262,
"text": "C:\\Users\\msaur\\Desktop>dart --enable-asserts GeeksForGeeks.dart\nUnhandled exception:\n'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek != \n\"Geeks For Geeks\"': Strings are equal So this message is been displayed!!\n#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)\n#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)\n#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)\n#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)\n#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)\n\n"
},
{
"code": null,
"e": 26941,
"s": 26921,
"text": "Output through cmd:"
},
{
"code": null,
"e": 26965,
"s": 26941,
"text": "Dart-Exception-Handling"
},
{
"code": null,
"e": 26970,
"s": 26965,
"text": "Dart"
},
{
"code": null,
"e": 27068,
"s": 26970,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27100,
"s": 27068,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 27139,
"s": 27100,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 27165,
"s": 27139,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 27198,
"s": 27165,
"text": "Flutter - Row and Column Widgets"
},
{
"code": null,
"e": 27212,
"s": 27198,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 27239,
"s": 27212,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 27265,
"s": 27239,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 27291,
"s": 27265,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 27318,
"s": 27291,
"text": "Container class in Flutter"
}
]
|
Bundle in Android with Example - GeeksforGeeks | 05 May, 2021
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key. Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.
The following are the major types that are passed/retrieved to/from a Bundle:
putInt(String key, int value), getInt(String key, int value)
putString(String key, String value), getString(String key, String value)
putStringArray(String key, String[] value), getStringArray(String key, String[] value)
putChar(String key, char value), getChar(String key, char value)
putBoolean(String key, boolean value), getBoolean(String key, boolean value)
The bundle is always used with Intent in Android. Now to use Bundle writes the below code in the MainActivity.
Java
Kotlin
// creating a intentIntent intent = new Intent(this, SecondActivity.class); // creating a bundle objectBundle bundle = new Bundle(); // storing the string value in the bundle// which is mapped to keybundle.putString("key1", "GFG :- Main Activity"); // passing the bundle into the intentintent.putExtras(bundle); // starting the intentstartActivity(intent);
// creating the instance of the bundleval bundle = Bundle() // storing the string value in the bundle// which is mapped to keybundle.putString("key1", "Gfg :- Main Activity") // creating a intentintent = Intent(this@MainActivity, SecondActivity::class.java) // passing a bundle to the intentintent.putExtras(bundle) // starting the activity by passing the intent to it.startActivity(intent)
Now create another empty activity named SecondActivity. Now to retrieve the data stored in the Bundle, write the following code in SecondActivity.
Java
Kotlin
// getting the bundle back from the androidBundle bundle = getIntent().getExtras(); // getting the string backString title = bundle.getString("key1", "Default");
// getting the bundle back from the androidval bundle = intent.extras // performing the safety null checkvar s:String? = null // getting the string backs = bundle!!.getString("key1", "Default"))
Alternatively, if one does not want to use the default value too, one can do this but remember it gives an exception.
For eg: boolean b = bundle.getBoolean(“pass the key here”);
If there exists no mapping corresponding to the key, it may lead to NullPointerException. Hence it’s recommended to add default values for the Bundle.
Step 1: Create a new project
Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need.
Click on File, then New => New Project.
Choose Empty activity
Select language as Java/Kotlin
Select the minimum SDK as per your need.
Step 2: Working with the activity_main.xml file
Now add two Buttons into the app, one button will pass the data which is stored into the bundle, and another button will pass the empty bundle, ie clearing the bundle with bundle.clear() and then passing the Bundle to Intent. The complete code for the activity_main.xml file is given below. Here one can see that the first button is used to pass the non-empty bundle, while the second button is used to pass the empty bundle.
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:padding="10dp" tools:context=".MainActivity"> <Button android:id="@+id/btnPassBundles" android:layout_width="275dp" android:layout_height="101dp" android:layout_marginTop="250dp" android:text="Pass Data Into Bundle" android:textSize="24sp" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnNoPassBundle" android:layout_width="277dp" android:layout_height="92dp" android:layout_marginBottom="220dp" android:layout_marginTop="75dp" android:text="Pass No Data/Empty BUNDLE" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/btnPassBundles" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create another activity and named it as SecondActivity
Now create another empty activity names SecondActivity. Follow the procedure illustrated in the image given below to create another activity.
Step 4: Working with the activity_second.xml file
In this file add a TextView to display the text in the SecondActivity.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SecondActivity"> <TextView android:id="@+id/txtString" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="348dp" android:text="String from MainActivity" android:textSize="40sp" android:textStyle="bold" android:gravity="center" android:textColor="#008000" app:layout_constraintHorizontal_bias="0.428" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Working with the MainActivity file
The complete code for the MainActivity is given below. Comments are added to understand the code easily.
Java
Kotlin
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnPassBundles, btnNoPassBundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnPassBundles = findViewById(R.id.btnPassBundles); btnNoPassBundle = findViewById(R.id.btnNoPassBundle); // one button will pass the bundle and other button // will not pass the bundle btnPassBundles.setOnClickListener(this); btnNoPassBundle.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnPassBundles: // creating a bundle instance Bundle bundle = new Bundle(); // passing the data into the bundle bundle.putString( "key1", "Passing Bundle From Main Activity to 2nd Activity"); Intent intent = new Intent(MainActivity.this, SecondActivity.class); // passing the bundle to the intent intent.putExtras(bundle); // starting the activity by passing the intent // to it. startActivity(intent); break; case R.id.btnNoPassBundle: bundle = new Bundle(); bundle.putString( "key1", "Not passing Bundle From Main Activity"); // clearing the data stored into the bundle bundle.clear(); // passing the intent to the second activity intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtras(bundle); startActivity(intent); break; } }}
import android.content.Intentimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), View.OnClickListener { var btnPassBundles: Button? = null var btnNoPassBundle: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnPassBundles = findViewById(R.id.btnPassBundles) btnNoPassBundle = findViewById(R.id.btnNoPassBundle) // one button will pass the bundle and other button // will not pass the bundle btnPassBundles?.setOnClickListener(this) btnNoPassBundle?.setOnClickListener(this) } override fun onClick(view: View) { when (view.id) { R.id.btnPassBundles -> { // creating the bundle instance val bundle = Bundle() // passing the data into the bundle bundle.putString("key1", "Passing Bundle From Main Activity to 2nd Activity") val intent = Intent(this@MainActivity, SecondActivity::class.java) intent.putExtras(bundle) startActivity(intent) } R.id.btnNoPassBundle -> { val bundle = Bundle() bundle.putString("key1", "Not passing Bundle From Main Activity") // clearing the bundle bundle.clear() // passing the intent to the second activity intent = Intent(this@MainActivity, SecondActivity::class.java) // passing the bundle into the intent intent.putExtras(bundle) startActivity(intent) } } }}
Step 6: Working with the SecondActivity file
The complete code for the SecondActivity is given below. Comments are added to understand the code easily.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class SecondActivity extends AppCompatActivity { TextView txtString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); txtString = findViewById(R.id.txtString); // getting the bundle from the intent Bundle bundle = getIntent().getExtras(); // setting the text in the textview txtString.setText(bundle.getString("key1", "No value from the MainActivity")); }}
import android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { var txtString: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) txtString = findViewById(R.id.txtString) txtBoolean = findViewById(R.id.txtBoolean) // getting the bundle from the intent val bundle = intent.extras // setting the text in the textview txtString?.setText(bundle!!.getString("key1", "No value from MainActivity :(")) }}
sweetyty
android
Android
Java
Kotlin
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java | [
{
"code": null,
"e": 24480,
"s": 24452,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25270,
"s": 24480,
"text": "It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key. Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity."
},
{
"code": null,
"e": 25348,
"s": 25270,
"text": "The following are the major types that are passed/retrieved to/from a Bundle:"
},
{
"code": null,
"e": 25409,
"s": 25348,
"text": "putInt(String key, int value), getInt(String key, int value)"
},
{
"code": null,
"e": 25482,
"s": 25409,
"text": "putString(String key, String value), getString(String key, String value)"
},
{
"code": null,
"e": 25569,
"s": 25482,
"text": "putStringArray(String key, String[] value), getStringArray(String key, String[] value)"
},
{
"code": null,
"e": 25634,
"s": 25569,
"text": "putChar(String key, char value), getChar(String key, char value)"
},
{
"code": null,
"e": 25711,
"s": 25634,
"text": "putBoolean(String key, boolean value), getBoolean(String key, boolean value)"
},
{
"code": null,
"e": 25822,
"s": 25711,
"text": "The bundle is always used with Intent in Android. Now to use Bundle writes the below code in the MainActivity."
},
{
"code": null,
"e": 25827,
"s": 25822,
"text": "Java"
},
{
"code": null,
"e": 25834,
"s": 25827,
"text": "Kotlin"
},
{
"code": "// creating a intentIntent intent = new Intent(this, SecondActivity.class); // creating a bundle objectBundle bundle = new Bundle(); // storing the string value in the bundle// which is mapped to keybundle.putString(\"key1\", \"GFG :- Main Activity\"); // passing the bundle into the intentintent.putExtras(bundle); // starting the intentstartActivity(intent);",
"e": 26191,
"s": 25834,
"text": null
},
{
"code": "// creating the instance of the bundleval bundle = Bundle() // storing the string value in the bundle// which is mapped to keybundle.putString(\"key1\", \"Gfg :- Main Activity\") // creating a intentintent = Intent(this@MainActivity, SecondActivity::class.java) // passing a bundle to the intentintent.putExtras(bundle) // starting the activity by passing the intent to it.startActivity(intent)",
"e": 26582,
"s": 26191,
"text": null
},
{
"code": null,
"e": 26733,
"s": 26586,
"text": "Now create another empty activity named SecondActivity. Now to retrieve the data stored in the Bundle, write the following code in SecondActivity."
},
{
"code": null,
"e": 26740,
"s": 26735,
"text": "Java"
},
{
"code": null,
"e": 26747,
"s": 26740,
"text": "Kotlin"
},
{
"code": "// getting the bundle back from the androidBundle bundle = getIntent().getExtras(); // getting the string backString title = bundle.getString(\"key1\", \"Default\");",
"e": 26909,
"s": 26747,
"text": null
},
{
"code": "// getting the bundle back from the androidval bundle = intent.extras // performing the safety null checkvar s:String? = null // getting the string backs = bundle!!.getString(\"key1\", \"Default\"))",
"e": 27104,
"s": 26909,
"text": null
},
{
"code": null,
"e": 27226,
"s": 27108,
"text": "Alternatively, if one does not want to use the default value too, one can do this but remember it gives an exception."
},
{
"code": null,
"e": 27288,
"s": 27228,
"text": "For eg: boolean b = bundle.getBoolean(“pass the key here”);"
},
{
"code": null,
"e": 27443,
"s": 27292,
"text": "If there exists no mapping corresponding to the key, it may lead to NullPointerException. Hence it’s recommended to add default values for the Bundle."
},
{
"code": null,
"e": 27476,
"s": 27447,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 27609,
"s": 27478,
"text": "Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need."
},
{
"code": null,
"e": 27649,
"s": 27609,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 27671,
"s": 27649,
"text": "Choose Empty activity"
},
{
"code": null,
"e": 27702,
"s": 27671,
"text": "Select language as Java/Kotlin"
},
{
"code": null,
"e": 27743,
"s": 27702,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 27791,
"s": 27743,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28219,
"s": 27793,
"text": "Now add two Buttons into the app, one button will pass the data which is stored into the bundle, and another button will pass the empty bundle, ie clearing the bundle with bundle.clear() and then passing the Bundle to Intent. The complete code for the activity_main.xml file is given below. Here one can see that the first button is used to pass the non-empty bundle, while the second button is used to pass the empty bundle."
},
{
"code": null,
"e": 28225,
"s": 28221,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"10dp\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btnPassBundles\" android:layout_width=\"275dp\" android:layout_height=\"101dp\" android:layout_marginTop=\"250dp\" android:text=\"Pass Data Into Bundle\" android:textSize=\"24sp\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/btnNoPassBundle\" android:layout_width=\"277dp\" android:layout_height=\"92dp\" android:layout_marginBottom=\"220dp\" android:layout_marginTop=\"75dp\" android:text=\"Pass No Data/Empty BUNDLE\" android:textSize=\"24sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/btnPassBundles\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 29636,
"s": 28225,
"text": null
},
{
"code": null,
"e": 29703,
"s": 29640,
"text": "Step 3: Create another activity and named it as SecondActivity"
},
{
"code": null,
"e": 29847,
"s": 29705,
"text": "Now create another empty activity names SecondActivity. Follow the procedure illustrated in the image given below to create another activity."
},
{
"code": null,
"e": 29901,
"s": 29851,
"text": "Step 4: Working with the activity_second.xml file"
},
{
"code": null,
"e": 29974,
"s": 29903,
"text": "In this file add a TextView to display the text in the SecondActivity."
},
{
"code": null,
"e": 29980,
"s": 29976,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".SecondActivity\"> <TextView android:id=\"@+id/txtString\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"348dp\" android:text=\"String from MainActivity\" android:textSize=\"40sp\" android:textStyle=\"bold\" android:gravity=\"center\" android:textColor=\"#008000\" app:layout_constraintHorizontal_bias=\"0.428\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 30965,
"s": 29980,
"text": null
},
{
"code": null,
"e": 31012,
"s": 30969,
"text": "Step 5: Working with the MainActivity file"
},
{
"code": null,
"e": 31119,
"s": 31014,
"text": "The complete code for the MainActivity is given below. Comments are added to understand the code easily."
},
{
"code": null,
"e": 31126,
"s": 31121,
"text": "Java"
},
{
"code": null,
"e": 31133,
"s": 31126,
"text": "Kotlin"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnPassBundles, btnNoPassBundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnPassBundles = findViewById(R.id.btnPassBundles); btnNoPassBundle = findViewById(R.id.btnNoPassBundle); // one button will pass the bundle and other button // will not pass the bundle btnPassBundles.setOnClickListener(this); btnNoPassBundle.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnPassBundles: // creating a bundle instance Bundle bundle = new Bundle(); // passing the data into the bundle bundle.putString( \"key1\", \"Passing Bundle From Main Activity to 2nd Activity\"); Intent intent = new Intent(MainActivity.this, SecondActivity.class); // passing the bundle to the intent intent.putExtras(bundle); // starting the activity by passing the intent // to it. startActivity(intent); break; case R.id.btnNoPassBundle: bundle = new Bundle(); bundle.putString( \"key1\", \"Not passing Bundle From Main Activity\"); // clearing the data stored into the bundle bundle.clear(); // passing the intent to the second activity intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtras(bundle); startActivity(intent); break; } }}",
"e": 33195,
"s": 31133,
"text": null
},
{
"code": "import android.content.Intentimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), View.OnClickListener { var btnPassBundles: Button? = null var btnNoPassBundle: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnPassBundles = findViewById(R.id.btnPassBundles) btnNoPassBundle = findViewById(R.id.btnNoPassBundle) // one button will pass the bundle and other button // will not pass the bundle btnPassBundles?.setOnClickListener(this) btnNoPassBundle?.setOnClickListener(this) } override fun onClick(view: View) { when (view.id) { R.id.btnPassBundles -> { // creating the bundle instance val bundle = Bundle() // passing the data into the bundle bundle.putString(\"key1\", \"Passing Bundle From Main Activity to 2nd Activity\") val intent = Intent(this@MainActivity, SecondActivity::class.java) intent.putExtras(bundle) startActivity(intent) } R.id.btnNoPassBundle -> { val bundle = Bundle() bundle.putString(\"key1\", \"Not passing Bundle From Main Activity\") // clearing the bundle bundle.clear() // passing the intent to the second activity intent = Intent(this@MainActivity, SecondActivity::class.java) // passing the bundle into the intent intent.putExtras(bundle) startActivity(intent) } } }}",
"e": 35010,
"s": 33195,
"text": null
},
{
"code": null,
"e": 35059,
"s": 35014,
"text": "Step 6: Working with the SecondActivity file"
},
{
"code": null,
"e": 35168,
"s": 35061,
"text": "The complete code for the SecondActivity is given below. Comments are added to understand the code easily."
},
{
"code": null,
"e": 35175,
"s": 35170,
"text": "Java"
},
{
"code": null,
"e": 35182,
"s": 35175,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class SecondActivity extends AppCompatActivity { TextView txtString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); txtString = findViewById(R.id.txtString); // getting the bundle from the intent Bundle bundle = getIntent().getExtras(); // setting the text in the textview txtString.setText(bundle.getString(\"key1\", \"No value from the MainActivity\")); }}",
"e": 35833,
"s": 35182,
"text": null
},
{
"code": "import android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { var txtString: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) txtString = findViewById(R.id.txtString) txtBoolean = findViewById(R.id.txtBoolean) // getting the bundle from the intent val bundle = intent.extras // setting the text in the textview txtString?.setText(bundle!!.getString(\"key1\", \"No value from MainActivity :(\")) }}",
"e": 36505,
"s": 35833,
"text": null
},
{
"code": null,
"e": 36519,
"s": 36510,
"text": "sweetyty"
},
{
"code": null,
"e": 36527,
"s": 36519,
"text": "android"
},
{
"code": null,
"e": 36535,
"s": 36527,
"text": "Android"
},
{
"code": null,
"e": 36540,
"s": 36535,
"text": "Java"
},
{
"code": null,
"e": 36547,
"s": 36540,
"text": "Kotlin"
},
{
"code": null,
"e": 36552,
"s": 36547,
"text": "Java"
},
{
"code": null,
"e": 36560,
"s": 36552,
"text": "Android"
},
{
"code": null,
"e": 36658,
"s": 36560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36667,
"s": 36658,
"text": "Comments"
},
{
"code": null,
"e": 36680,
"s": 36667,
"text": "Old Comments"
},
{
"code": null,
"e": 36738,
"s": 36680,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 36781,
"s": 36738,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 36823,
"s": 36781,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 36854,
"s": 36823,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 36883,
"s": 36854,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 36898,
"s": 36883,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36942,
"s": 36898,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36964,
"s": 36942,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37000,
"s": 36964,
"text": "Arrays.sort() in Java with examples"
}
]
|
Find height of a special binary tree whose leaf nodes are connected - GeeksforGeeks | 31 Mar, 2022
Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, find its height.
For example,
1
/ \
2 3
/ \
4 5
/
6
In the above binary tree, 6, 5 and 3 are leaf nodes and they form a circular doubly linked list. Here, the left pointer of leaf node will act as a previous pointer of circular doubly linked list and its right pointer will act as next pointer of circular doubly linked list.
The idea is to follow similar approach as we do for finding height of a normal binary tree. We recursively calculate height of left and right subtrees of a node and assign height to the node as max of the heights of two children plus 1. But left and right child of a leaf node are null for normal binary trees. But, here leaf node is a circular doubly linked list node. So for a node to be a leaf node, we check if node’s left’s right is pointing to the node and its right’s left is also pointing to the node itself.
Below is the implementation of above idea –
C++
Java
Python3
C#
Javascript
// C++ program to calculate height of a special tree// whose leaf nodes forms a circular doubly linked list#include <bits/stdc++.h>using namespace std; // A binary tree Nodestruct Node { int data; Node *left, *right;}; // function to check if given node is a leaf node or nodebool isLeaf(Node* node){ // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return node->left && node->left->right == node && node->right && node->right->left == node;} /* Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node.*/int maxDepth(Node* node){ // if node is NULL, return 0 if (node == NULL) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take maximum return 1 + max(maxDepth(node->left), maxDepth(node->right));} // Helper function that allocates a new tree nodeNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return node;} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(6); // Given tree contains 3 leaf nodes Node* L1 = root->left->left->left; Node* L2 = root->left->right; Node* L3 = root->right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1->right = L2, L2->right = L3, L3->right = L1; // set prev pointer of linked list L3->left = L2, L2->left = L1, L1->left = L3; // calculate height of the tree cout << "Height of tree is " << maxDepth(root); return 0;}
// Java implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listimport java.io.*;import java.util.*; // User defined node classclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // function to check if given node is a leaf node or // node static boolean isLeaf(Node node) { // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node); } /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(Node node) { // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.max(maxDepth(node.left), maxDepth(node.right)); } // Driver code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(6); // Given tree contains 3 leaf nodes Node L1 = root.left.left.left; Node L2 = root.left.right; Node L3 = root.right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1.right = L2; L2.right = L3; L3.right = L1; // set prev pointer of linked list L3.left = L2; L2.left = L1; L1.left = L3; // calculate height of the tree System.out.println("Height of tree is " + maxDepth(root)); }}// This code is contributed by rachana soma
""" program to Delete a Tree """ # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # function to check if given node is a leaf node or node def isLeaf(node): # If given node's left's right is pointing to given node # and its right's left is pointing to the node itself # then it's a leaf return node.left and node.left.right == node and \ node.right and node.right.left == node """ Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node.""" def maxDepth(node): # if node is None, return 0 if (node == None): return 0 # if node is a leaf node, return 1 if (isLeaf(node)): return 1 # compute the depth of each subtree and take maximum return 1 + max(maxDepth(node.left), maxDepth(node.right)) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.left.left = newNode(6) # Given tree contains 3 leaf nodes L1 = root.left.left.left L2 = root.left.right L3 = root.right # create circular doubly linked list out of # leaf nodes of the tree # set next pointer of linked list L1.right = L2 L2.right = L3 L3.right = L1 # set prev pointer of linked list L3.left = L2 L2.left = L1 L1.left = L3 # calculate height of the tree print("Height of tree is ", maxDepth(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listusing System; // User defined node classpublic class Node { public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} public class GFG { // function to check if given node is a leaf node or // node static bool isLeaf(Node node) { // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node); } /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(Node node) { // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.Max(maxDepth(node.left), maxDepth(node.right)); } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(6); // Given tree contains 3 leaf nodes Node L1 = root.left.left.left; Node L2 = root.left.right; Node L3 = root.right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1.right = L2; L2.right = L3; L3.right = L1; // set prev pointer of linked list L3.left = L2; L2.left = L1; L1.left = L3; // calculate height of the tree Console.WriteLine("Height of tree is " + maxDepth(root)); }} // This code is contributed by 29AjayKumar
<script>// Javascript implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listclass Node{ constructor(key) { this.data = key; this.left = this.right = null; }} // function to check if given node is a leaf node or // nodefunction isLeaf(node){ // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node);} /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/function maxDepth(node){ // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.left.left = new Node(6); // Given tree contains 3 leaf nodeslet L1 = root.left.left.left;let L2 = root.left.right;let L3 = root.right; // create circular doubly linked list out of// leaf nodes of the tree // set next pointer of linked listL1.right = L2;L2.right = L3;L3.right = L1; // set prev pointer of linked listL3.left = L2;L2.left = L1;L1.left = L3; // calculate height of the treedocument.write("Height of tree is " + maxDepth(root)); // This code is contributed by rag2127</script>
Output:
Height of tree is 4
YouTubeGeeksforGeeks507K subscribersFind height of a special binary tree whose leaf nodes are connected | 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 / 3:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bCUSbEYWv-o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rachana soma
SHUBHAMSINGH10
29AjayKumar
pragup
rag2127
saurabh1990aror
simmytarika5
Amazon
Tree
Amazon
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Top 50 Tree Coding Problems for Interviews
Find the node with minimum value in a Binary Search Tree
Print Binary Tree in 2-Dimensions
Real-time application of Data Structures
Threaded Binary Tree
Difference between Min Heap and Max Heap
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Find maximum (or minimum) in Binary Tree | [
{
"code": null,
"e": 26295,
"s": 26267,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 26410,
"s": 26295,
"text": "Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, find its height."
},
{
"code": null,
"e": 26424,
"s": 26410,
"text": "For example, "
},
{
"code": null,
"e": 26497,
"s": 26424,
"text": " 1 \n / \\ \n 2 3 \n / \\ \n 4 5\n / \n 6 "
},
{
"code": null,
"e": 26772,
"s": 26497,
"text": "In the above binary tree, 6, 5 and 3 are leaf nodes and they form a circular doubly linked list. Here, the left pointer of leaf node will act as a previous pointer of circular doubly linked list and its right pointer will act as next pointer of circular doubly linked list. "
},
{
"code": null,
"e": 27289,
"s": 26772,
"text": "The idea is to follow similar approach as we do for finding height of a normal binary tree. We recursively calculate height of left and right subtrees of a node and assign height to the node as max of the heights of two children plus 1. But left and right child of a leaf node are null for normal binary trees. But, here leaf node is a circular doubly linked list node. So for a node to be a leaf node, we check if node’s left’s right is pointing to the node and its right’s left is also pointing to the node itself."
},
{
"code": null,
"e": 27335,
"s": 27289,
"text": "Below is the implementation of above idea – "
},
{
"code": null,
"e": 27339,
"s": 27335,
"text": "C++"
},
{
"code": null,
"e": 27344,
"s": 27339,
"text": "Java"
},
{
"code": null,
"e": 27352,
"s": 27344,
"text": "Python3"
},
{
"code": null,
"e": 27355,
"s": 27352,
"text": "C#"
},
{
"code": null,
"e": 27366,
"s": 27355,
"text": "Javascript"
},
{
"code": "// C++ program to calculate height of a special tree// whose leaf nodes forms a circular doubly linked list#include <bits/stdc++.h>using namespace std; // A binary tree Nodestruct Node { int data; Node *left, *right;}; // function to check if given node is a leaf node or nodebool isLeaf(Node* node){ // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return node->left && node->left->right == node && node->right && node->right->left == node;} /* Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node.*/int maxDepth(Node* node){ // if node is NULL, return 0 if (node == NULL) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take maximum return 1 + max(maxDepth(node->left), maxDepth(node->right));} // Helper function that allocates a new tree nodeNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return node;} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(6); // Given tree contains 3 leaf nodes Node* L1 = root->left->left->left; Node* L2 = root->left->right; Node* L3 = root->right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1->right = L2, L2->right = L3, L3->right = L1; // set prev pointer of linked list L3->left = L2, L2->left = L1, L1->left = L3; // calculate height of the tree cout << \"Height of tree is \" << maxDepth(root); return 0;}",
"e": 29273,
"s": 27366,
"text": null
},
{
"code": "// Java implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listimport java.io.*;import java.util.*; // User defined node classclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // function to check if given node is a leaf node or // node static boolean isLeaf(Node node) { // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node); } /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(Node node) { // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.max(maxDepth(node.left), maxDepth(node.right)); } // Driver code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(6); // Given tree contains 3 leaf nodes Node L1 = root.left.left.left; Node L2 = root.left.right; Node L3 = root.right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1.right = L2; L2.right = L3; L3.right = L1; // set prev pointer of linked list L3.left = L2; L2.left = L1; L1.left = L3; // calculate height of the tree System.out.println(\"Height of tree is \" + maxDepth(root)); }}// This code is contributed by rachana soma",
"e": 31478,
"s": 29273,
"text": null
},
{
"code": "\"\"\" program to Delete a Tree \"\"\" # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # function to check if given node is a leaf node or node def isLeaf(node): # If given node's left's right is pointing to given node # and its right's left is pointing to the node itself # then it's a leaf return node.left and node.left.right == node and \\ node.right and node.right.left == node \"\"\" Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node.\"\"\" def maxDepth(node): # if node is None, return 0 if (node == None): return 0 # if node is a leaf node, return 1 if (isLeaf(node)): return 1 # compute the depth of each subtree and take maximum return 1 + max(maxDepth(node.left), maxDepth(node.right)) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.left.left = newNode(6) # Given tree contains 3 leaf nodes L1 = root.left.left.left L2 = root.left.right L3 = root.right # create circular doubly linked list out of # leaf nodes of the tree # set next pointer of linked list L1.right = L2 L2.right = L3 L3.right = L1 # set prev pointer of linked list L3.left = L2 L2.left = L1 L1.left = L3 # calculate height of the tree print(\"Height of tree is \", maxDepth(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 33217,
"s": 31478,
"text": null
},
{
"code": "// C# implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listusing System; // User defined node classpublic class Node { public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} public class GFG { // function to check if given node is a leaf node or // node static bool isLeaf(Node node) { // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node); } /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(Node node) { // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.Max(maxDepth(node.left), maxDepth(node.right)); } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.left.left.left = new Node(6); // Given tree contains 3 leaf nodes Node L1 = root.left.left.left; Node L2 = root.left.right; Node L3 = root.right; // create circular doubly linked list out of // leaf nodes of the tree // set next pointer of linked list L1.right = L2; L2.right = L3; L3.right = L1; // set prev pointer of linked list L3.left = L2; L2.left = L1; L1.left = L3; // calculate height of the tree Console.WriteLine(\"Height of tree is \" + maxDepth(root)); }} // This code is contributed by 29AjayKumar",
"e": 35427,
"s": 33217,
"text": null
},
{
"code": "<script>// Javascript implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listclass Node{ constructor(key) { this.data = key; this.left = this.right = null; }} // function to check if given node is a leaf node or // nodefunction isLeaf(node){ // If given node's left's right is pointing to given // node and its right's left is pointing to the node // itself then it's a leaf return (node.left != null && node.left.right == node && node.right != null && node.right.left == node);} /* Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node.*/function maxDepth(node){ // if node is NULL, return 0 if (node == null) return 0; // if node is a leaf node, return 1 if (isLeaf(node)) return 1; // compute the depth of each subtree and take // maximum return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));} // Driver codelet root = new Node(1); root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.left.left = new Node(6); // Given tree contains 3 leaf nodeslet L1 = root.left.left.left;let L2 = root.left.right;let L3 = root.right; // create circular doubly linked list out of// leaf nodes of the tree // set next pointer of linked listL1.right = L2;L2.right = L3;L3.right = L1; // set prev pointer of linked listL3.left = L2;L2.left = L1;L1.left = L3; // calculate height of the treedocument.write(\"Height of tree is \" + maxDepth(root)); // This code is contributed by rag2127</script>",
"e": 37218,
"s": 35427,
"text": null
},
{
"code": null,
"e": 37227,
"s": 37218,
"text": "Output: "
},
{
"code": null,
"e": 37247,
"s": 37227,
"text": "Height of tree is 4"
},
{
"code": null,
"e": 38113,
"s": 37247,
"text": "YouTubeGeeksforGeeks507K subscribersFind height of a special binary tree whose leaf nodes are connected | 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 / 3:03•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bCUSbEYWv-o\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 38154,
"s": 38113,
"text": "&list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk"
},
{
"code": null,
"e": 38573,
"s": 38154,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38588,
"s": 38575,
"text": "rachana soma"
},
{
"code": null,
"e": 38603,
"s": 38588,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 38615,
"s": 38603,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38622,
"s": 38615,
"text": "pragup"
},
{
"code": null,
"e": 38630,
"s": 38622,
"text": "rag2127"
},
{
"code": null,
"e": 38646,
"s": 38630,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 38659,
"s": 38646,
"text": "simmytarika5"
},
{
"code": null,
"e": 38666,
"s": 38659,
"text": "Amazon"
},
{
"code": null,
"e": 38671,
"s": 38666,
"text": "Tree"
},
{
"code": null,
"e": 38678,
"s": 38671,
"text": "Amazon"
},
{
"code": null,
"e": 38683,
"s": 38678,
"text": "Tree"
},
{
"code": null,
"e": 38781,
"s": 38683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38817,
"s": 38781,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38857,
"s": 38817,
"text": "DFS traversal of a tree using recursion"
},
{
"code": null,
"e": 38900,
"s": 38857,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 38957,
"s": 38900,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 38991,
"s": 38957,
"text": "Print Binary Tree in 2-Dimensions"
},
{
"code": null,
"e": 39032,
"s": 38991,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 39053,
"s": 39032,
"text": "Threaded Binary Tree"
},
{
"code": null,
"e": 39094,
"s": 39053,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 39164,
"s": 39094,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
}
]
|
How to Convert XML data into JSON using PHP ? - GeeksforGeeks | 13 Apr, 2021
In this article, we are going to see how to convert XML data into JSON format using PHP.
Requirements:
XAMPP Server
Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data.
Structure of XML:
<root>
<child>
<subchild> ... </subchild>
</child>
</root>
Example: We are considering student XML data and converting it into JSON format.
<student>
<details>
<address>
<firstname>sravan kumar</firstname>
<city>kakumanu</city>
<zip>522112</zip>
</address>
</details>
<details>
<address>
<firstname>sudheer</firstname>
<city>guntur</city>
<zip>522112</zip>
</address>
</details>
<details>
<address>
<firstname>radha kumar</firstname>
<city>ponnur</city>
<zip>456345</zip>
</address>
</details>
<details>
<address>
<firstname>vani</firstname>
<city>noida</city>
<zip>456644</zip>
</address>
</details>
</student>
JSON stands for JavaScript Object notation which is in the format of array-like structure.
Structure of JSON:
{
"data1": "value1",
"data2": "value2",
"datan": "valuen"
}
Example:
{"details":
[{
"address": {
"firstname": "sravan kumar",
"city": "kakumanu",
"zip": "522112"
}
},
{
"address": {
"firstname": "sudheer",
"city": "guntur",
"zip": "522112"
}
},
{
"address": {
"firstname": "radha kumar",
"city": "ponnur",
"zip": "456345"
}
},
{
"address": {
"firstname": "vani",
"city": "noida",
"zip": "456644"
}
}]}
Similarities of JSON and XML:
Both JSON and XML are self-describing.
JSON and XML are hierarchical.
JSON and XML can be parsed which are used in many programming languages.
Differences between JSON and XML:
Used Methods:
simplexml_load_string() Method: This function is used to convert the XML string into an object.
json_encode() Method: This function is used to encode a value to JSON format.
Steps:
Start XAMPP server
Open notepad and type the following code and save it as base.php in xampp-htdocs folder.
PHP code: The following is the content for the file “base.php” file.
PHP
<?php // student details xml data taken as an String$xml = '<?xml version="1.0" encoding="utf-8"?><student> <details> <address> <firstname>sravan kumar</firstname> <city>kakumanu</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>sudheer</firstname> <city>guntur</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>radha kumar</firstname> <city>ponnur</city> <zip>456345</zip> </address> </details> <details> <address> <firstname>vani</firstname> <city>noida</city> <zip>456644</zip> </address> </details></student>'; // Load xml data into xml data object$xmldata = simplexml_load_string($xml); // Encode this xml data into json // using json_encoe function$jsondata = json_encode($xmldata); // Display json dataprint_r($jsondata); ?>
Output: Type localhost/base.php in your browser.
{
"details": [
{
"address": {
"firstname": "sravan kumar",
"city": "kakumanu",
"zip": "522112"
}},
{
"address": {
"firstname": "sudheer",
"city": "guntur",
"zip": "522112"
}},
{ "address": {
"firstname": "radha kumar",
"city": "ponnur",
"zip": "456345"
}},
{ "address": {
"firstname": "vani",
"city": "noida",
"zip": "456644"
}}
]
}
JSON
PHP-function
PHP-Questions
PHP-XML
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 32761,
"s": 32733,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 32850,
"s": 32761,
"text": "In this article, we are going to see how to convert XML data into JSON format using PHP."
},
{
"code": null,
"e": 32864,
"s": 32850,
"text": "Requirements:"
},
{
"code": null,
"e": 32877,
"s": 32864,
"text": "XAMPP Server"
},
{
"code": null,
"e": 33093,
"s": 32877,
"text": "Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data."
},
{
"code": null,
"e": 33111,
"s": 33093,
"text": "Structure of XML:"
},
{
"code": null,
"e": 33180,
"s": 33111,
"text": "<root> \n <child>\n <subchild> ... </subchild>\n </child>\n</root>\n"
},
{
"code": null,
"e": 33263,
"s": 33182,
"text": "Example: We are considering student XML data and converting it into JSON format."
},
{
"code": null,
"e": 33979,
"s": 33263,
"text": "<student>\n <details>\n <address>\n <firstname>sravan kumar</firstname>\n <city>kakumanu</city>\n <zip>522112</zip>\n </address>\n </details>\n\n <details>\n <address>\n <firstname>sudheer</firstname>\n <city>guntur</city>\n <zip>522112</zip>\n </address>\n </details>\n\n <details>\n <address>\n <firstname>radha kumar</firstname>\n <city>ponnur</city>\n <zip>456345</zip>\n </address>\n </details>\n\n <details>\n <address>\n <firstname>vani</firstname>\n <city>noida</city>\n <zip>456644</zip>\n </address>\n </details>\n</student>\n"
},
{
"code": null,
"e": 34070,
"s": 33979,
"text": "JSON stands for JavaScript Object notation which is in the format of array-like structure."
},
{
"code": null,
"e": 34089,
"s": 34070,
"text": "Structure of JSON:"
},
{
"code": null,
"e": 34163,
"s": 34089,
"text": "{ \n \"data1\": \"value1\",\n \"data2\": \"value2\",\n \"datan\": \"valuen\"\n}\n"
},
{
"code": null,
"e": 34172,
"s": 34163,
"text": "Example:"
},
{
"code": null,
"e": 34657,
"s": 34172,
"text": "{\"details\":\n[{ \n \"address\": { \n \"firstname\": \"sravan kumar\", \n \"city\": \"kakumanu\", \n \"zip\": \"522112\" \n }\n},\n{ \n \"address\": { \n \"firstname\": \"sudheer\", \n \"city\": \"guntur\", \n \"zip\": \"522112\" \n } \n},\n{ \n \"address\": { \n \"firstname\": \"radha kumar\", \n \"city\": \"ponnur\", \n \"zip\": \"456345\" \n } \n},\n{ \n \"address\": { \n \"firstname\": \"vani\", \n \"city\": \"noida\", \n \"zip\": \"456644\" \n } \n}]}\n"
},
{
"code": null,
"e": 34687,
"s": 34657,
"text": "Similarities of JSON and XML:"
},
{
"code": null,
"e": 34726,
"s": 34687,
"text": "Both JSON and XML are self-describing."
},
{
"code": null,
"e": 34757,
"s": 34726,
"text": "JSON and XML are hierarchical."
},
{
"code": null,
"e": 34830,
"s": 34757,
"text": "JSON and XML can be parsed which are used in many programming languages."
},
{
"code": null,
"e": 34864,
"s": 34830,
"text": "Differences between JSON and XML:"
},
{
"code": null,
"e": 34878,
"s": 34864,
"text": "Used Methods:"
},
{
"code": null,
"e": 34974,
"s": 34878,
"text": "simplexml_load_string() Method: This function is used to convert the XML string into an object."
},
{
"code": null,
"e": 35052,
"s": 34974,
"text": "json_encode() Method: This function is used to encode a value to JSON format."
},
{
"code": null,
"e": 35059,
"s": 35052,
"text": "Steps:"
},
{
"code": null,
"e": 35078,
"s": 35059,
"text": "Start XAMPP server"
},
{
"code": null,
"e": 35167,
"s": 35078,
"text": "Open notepad and type the following code and save it as base.php in xampp-htdocs folder."
},
{
"code": null,
"e": 35236,
"s": 35167,
"text": "PHP code: The following is the content for the file “base.php” file."
},
{
"code": null,
"e": 35240,
"s": 35236,
"text": "PHP"
},
{
"code": "<?php // student details xml data taken as an String$xml = '<?xml version=\"1.0\" encoding=\"utf-8\"?><student> <details> <address> <firstname>sravan kumar</firstname> <city>kakumanu</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>sudheer</firstname> <city>guntur</city> <zip>522112</zip> </address> </details> <details> <address> <firstname>radha kumar</firstname> <city>ponnur</city> <zip>456345</zip> </address> </details> <details> <address> <firstname>vani</firstname> <city>noida</city> <zip>456644</zip> </address> </details></student>'; // Load xml data into xml data object$xmldata = simplexml_load_string($xml); // Encode this xml data into json // using json_encoe function$jsondata = json_encode($xmldata); // Display json dataprint_r($jsondata); ?>",
"e": 36247,
"s": 35240,
"text": null
},
{
"code": null,
"e": 36296,
"s": 36247,
"text": "Output: Type localhost/base.php in your browser."
},
{
"code": null,
"e": 36887,
"s": 36296,
"text": "{\n \"details\": [\n { \n \"address\": { \n \"firstname\": \"sravan kumar\", \n \"city\": \"kakumanu\", \n \"zip\": \"522112\" \n }},\n { \n \"address\": { \n \"firstname\": \"sudheer\", \n \"city\": \"guntur\", \n \"zip\": \"522112\" \n }},\n { \"address\": { \n \"firstname\": \"radha kumar\", \n \"city\": \"ponnur\", \n \"zip\": \"456345\" \n }},\n { \"address\": { \n \"firstname\": \"vani\", \n \"city\": \"noida\", \n \"zip\": \"456644\" \n }}\n ]\n}"
},
{
"code": null,
"e": 36892,
"s": 36887,
"text": "JSON"
},
{
"code": null,
"e": 36905,
"s": 36892,
"text": "PHP-function"
},
{
"code": null,
"e": 36919,
"s": 36905,
"text": "PHP-Questions"
},
{
"code": null,
"e": 36927,
"s": 36919,
"text": "PHP-XML"
},
{
"code": null,
"e": 36931,
"s": 36927,
"text": "PHP"
},
{
"code": null,
"e": 36948,
"s": 36931,
"text": "Web Technologies"
},
{
"code": null,
"e": 36952,
"s": 36948,
"text": "PHP"
},
{
"code": null,
"e": 37050,
"s": 36952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37095,
"s": 37050,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 37145,
"s": 37095,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 37169,
"s": 37145,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 37209,
"s": 37169,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 37261,
"s": 37209,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 37301,
"s": 37261,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 37334,
"s": 37301,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 37379,
"s": 37334,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 37422,
"s": 37379,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
How do you get the length of a string in JQuery? - GeeksforGeeks | 12 Sep, 2019
The task is to get the length of a string with the help of JQuery. We can find the length of the string by the jQuery .length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string.
Syntax:
$(selector).length
Example 1:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Find Length of a String Using jQuery</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { var myStr = $("textarea").val(); if ($(this).hasClass("with-space")) { var withSpace = myStr.length; alert(withSpace); } else if ($(this).hasClass("without-space")) { var withoutSpace = myStr.replace(/ /g, '').length; alert(withoutSpace); } }); }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Enter Text and Click the Buttons</h3> <textarea rows="5" cols="60"> How do you get the length of a string in JQuery? </textarea> <br> <button type="button" class="with-space"> Length of string including white-spaces </button> <br> <br> <button type="button" class="without-space"> Length of string without white-spaces </button></body> </html>
Output:Before Click on the Button:
Example 2:
<!DOCTYPE html><html> <head> <title> Find Length of a String Using jQuery </title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script> $(function() { $('#geeks1').keyup(function() { var txtlen = $(this).val().length; var txtlennospace = $(this).val().replace(/\s+/g, '').length; $('#geeks1_space').text(txtlen); $('#geeks1_space_no_space').text(txtlennospace); }); }); </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <div style="padding-bottom: 10px;">JQuery - Realtime length</div> <div> <input style="padding: 7px;" maxlength="60" size="50" type="text" id="geeks1" /> <p>Length with space : <span id="geeks1_space"></span></p> <p>Length without space : <span id="geeks1_space_no_space"></span></p> </div></body> </html>
Output:Before Entering the Text:After Entering the Text:
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to Show and Hide div elements using radio buttons?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
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": 26376,
"s": 26348,
"text": "\n12 Sep, 2019"
},
{
"code": null,
"e": 26663,
"s": 26376,
"text": "The task is to get the length of a string with the help of JQuery. We can find the length of the string by the jQuery .length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string."
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Syntax:"
},
{
"code": null,
"e": 26690,
"s": 26671,
"text": "$(selector).length"
},
{
"code": null,
"e": 26701,
"s": 26690,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Find Length of a String Using jQuery</title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { var myStr = $(\"textarea\").val(); if ($(this).hasClass(\"with-space\")) { var withSpace = myStr.length; alert(withSpace); } else if ($(this).hasClass(\"without-space\")) { var withoutSpace = myStr.replace(/ /g, '').length; alert(withoutSpace); } }); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h3>Enter Text and Click the Buttons</h3> <textarea rows=\"5\" cols=\"60\"> How do you get the length of a string in JQuery? </textarea> <br> <button type=\"button\" class=\"with-space\"> Length of string including white-spaces </button> <br> <br> <button type=\"button\" class=\"without-space\"> Length of string without white-spaces </button></body> </html>",
"e": 27922,
"s": 26701,
"text": null
},
{
"code": null,
"e": 27957,
"s": 27922,
"text": "Output:Before Click on the Button:"
},
{
"code": null,
"e": 27968,
"s": 27957,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Find Length of a String Using jQuery </title> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script> $(function() { $('#geeks1').keyup(function() { var txtlen = $(this).val().length; var txtlennospace = $(this).val().replace(/\\s+/g, '').length; $('#geeks1_space').text(txtlen); $('#geeks1_space_no_space').text(txtlennospace); }); }); </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <div style=\"padding-bottom: 10px;\">JQuery - Realtime length</div> <div> <input style=\"padding: 7px;\" maxlength=\"60\" size=\"50\" type=\"text\" id=\"geeks1\" /> <p>Length with space : <span id=\"geeks1_space\"></span></p> <p>Length without space : <span id=\"geeks1_space_no_space\"></span></p> </div></body> </html>",
"e": 29164,
"s": 27968,
"text": null
},
{
"code": null,
"e": 29221,
"s": 29164,
"text": "Output:Before Entering the Text:After Entering the Text:"
},
{
"code": null,
"e": 29233,
"s": 29221,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29240,
"s": 29233,
"text": "Picked"
},
{
"code": null,
"e": 29247,
"s": 29240,
"text": "JQuery"
},
{
"code": null,
"e": 29264,
"s": 29247,
"text": "Web Technologies"
},
{
"code": null,
"e": 29291,
"s": 29264,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29389,
"s": 29291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29418,
"s": 29389,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29474,
"s": 29418,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 29529,
"s": 29474,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 29583,
"s": 29529,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 29617,
"s": 29583,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 29657,
"s": 29617,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29690,
"s": 29657,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29735,
"s": 29690,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29778,
"s": 29735,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Constructor Chaining In Java with Examples - GeeksforGeeks | 16 Aug, 2021
Prerequisite – Constructors in Java Constructor chaining is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways:
Within same class: It can be done using this() keyword for constructors in same class
From base class: by using super() keyword to call constructor from the base class.
Constructor chaining occurs through inheritance. A sub class constructor’s task is to call super class’s constructor first. This ensures that creation of sub class’s object starts with the initialization of the data members of the super class. There could be any numbers of classes in inheritance chain. Every constructor calls up the chain till class at the top is reached.Why do we need constructor chaining ? This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable.
Constructor Chaining within same class using this() keyword :
Java
// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}
Output:
75
5
The Default constructor
Rules of constructor chaining :
The this() expression should always be the first line of the constructor.There should be at-least be one constructor without the this() keyword (constructor 3 in above example).Constructor chaining can be achieved in any order.
The this() expression should always be the first line of the constructor.
There should be at-least be one constructor without the this() keyword (constructor 3 in above example).
Constructor chaining can be achieved in any order.
What happens if we change the order of constructors?Nothing, Constructor chaining can be achieved in any order
Java
// Java program to illustrate Constructor Chaining// within same class Using this() keyword// and changing order of constructorsclass Temp{ // default constructor 1 Temp() { System.out.println("default"); } // parameterized constructor 2 Temp(int x) { // invokes default constructor this(); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { // invokes parameterized constructor 2 this(5); System.out.println(x * y); } public static void main(String args[]) { // invokes parameterized constructor 3 new Temp(8, 10); }}
Output:
default
5
80
NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked at first. Hence, order in constructor chaining is not important.
Constructor Chaining to other class using super() keyword :
Java
// Java program to illustrate Constructor Chaining to// other class using super() keywordclass Base{ String name; // constructor 1 Base() { this(""); System.out.println("No-argument constructor of" + " base class"); } // constructor 2 Base(String name) { this.name = name; System.out.println("Calling parameterized constructor" + " of base"); }} class Derived extends Base{ // constructor 3 Derived() { System.out.println("No-argument constructor " + "of derived"); } // parameterized constructor 4 Derived(String name) { // invokes base class constructor 2 super(name); System.out.println("Calling parameterized " + "constructor of derived"); } public static void main(String args[]) { // calls parameterized constructor 4 Derived obj = new Derived("test"); // Calls No-argument constructor // Derived obj = new Derived(); }}
Output:
Calling parameterized constructor of base
Calling parameterized constructor of derived
Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super class’s constructor are invoked before the sub class’s constructor.Alternative method : using Init block : When we want certain common resources to be executed with every constructor we can put the code in the init block. Init block is always executed before any constructor, whenever a constructor is used for creating a new object.Example 1:
Java
class Temp{ // block to be executed before any constructor. { System.out.println("init block"); } // no-arg constructor Temp() { System.out.println("default"); } // constructor with one argument. Temp(int x) { System.out.println(x); } public static void main(String[] args) { // Object creation by calling no-argument // constructor. new Temp(); // Object creation by calling parameterized // constructor with one parameter. new Temp(10); }}
Output:
init block
default
init block
10
NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same class. See the ex. Example :
Java
class Temp{ // block to be executed first { System.out.println("init"); } Temp() { System.out.println("default"); } Temp(int x) { System.out.println(x); } // block to be executed after the first block // which has been defined above. { System.out.println("second"); } public static void main(String args[]) { new Temp(); new Temp(10); }}
Output :
init
second
default
init
second
10
This article is contributed by Apoorva singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vkbvipul
Vikramaditya Kukreja
nidhi_biet
anikakapoor
kalrap615
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Stream In Java
Reverse a string in Java
Arrays.sort() in Java with examples
How to iterate any Map in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 30305,
"s": 30277,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 30509,
"s": 30305,
"text": "Prerequisite – Constructors in Java Constructor chaining is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways: "
},
{
"code": null,
"e": 30595,
"s": 30509,
"text": "Within same class: It can be done using this() keyword for constructors in same class"
},
{
"code": null,
"e": 30678,
"s": 30595,
"text": "From base class: by using super() keyword to call constructor from the base class."
},
{
"code": null,
"e": 31349,
"s": 30678,
"text": "Constructor chaining occurs through inheritance. A sub class constructor’s task is to call super class’s constructor first. This ensures that creation of sub class’s object starts with the initialization of the data members of the super class. There could be any numbers of classes in inheritance chain. Every constructor calls up the chain till class at the top is reached.Why do we need constructor chaining ? This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable. "
},
{
"code": null,
"e": 31411,
"s": 31349,
"text": "Constructor Chaining within same class using this() keyword :"
},
{
"code": null,
"e": 31420,
"s": 31415,
"text": "Java"
},
{
"code": "// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println(\"The Default constructor\"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}",
"e": 32126,
"s": 31420,
"text": null
},
{
"code": null,
"e": 32136,
"s": 32126,
"text": "Output: "
},
{
"code": null,
"e": 32165,
"s": 32136,
"text": "75\n5\nThe Default constructor"
},
{
"code": null,
"e": 32198,
"s": 32165,
"text": "Rules of constructor chaining : "
},
{
"code": null,
"e": 32427,
"s": 32198,
"text": "The this() expression should always be the first line of the constructor.There should be at-least be one constructor without the this() keyword (constructor 3 in above example).Constructor chaining can be achieved in any order. "
},
{
"code": null,
"e": 32501,
"s": 32427,
"text": "The this() expression should always be the first line of the constructor."
},
{
"code": null,
"e": 32606,
"s": 32501,
"text": "There should be at-least be one constructor without the this() keyword (constructor 3 in above example)."
},
{
"code": null,
"e": 32658,
"s": 32606,
"text": "Constructor chaining can be achieved in any order. "
},
{
"code": null,
"e": 32769,
"s": 32658,
"text": "What happens if we change the order of constructors?Nothing, Constructor chaining can be achieved in any order"
},
{
"code": null,
"e": 32774,
"s": 32769,
"text": "Java"
},
{
"code": "// Java program to illustrate Constructor Chaining// within same class Using this() keyword// and changing order of constructorsclass Temp{ // default constructor 1 Temp() { System.out.println(\"default\"); } // parameterized constructor 2 Temp(int x) { // invokes default constructor this(); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { // invokes parameterized constructor 2 this(5); System.out.println(x * y); } public static void main(String args[]) { // invokes parameterized constructor 3 new Temp(8, 10); }}",
"e": 33430,
"s": 32774,
"text": null
},
{
"code": null,
"e": 33439,
"s": 33430,
"text": "Output: "
},
{
"code": null,
"e": 33452,
"s": 33439,
"text": "default\n5\n80"
},
{
"code": null,
"e": 33630,
"s": 33452,
"text": "NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked at first. Hence, order in constructor chaining is not important. "
},
{
"code": null,
"e": 33690,
"s": 33630,
"text": "Constructor Chaining to other class using super() keyword :"
},
{
"code": null,
"e": 33695,
"s": 33690,
"text": "Java"
},
{
"code": "// Java program to illustrate Constructor Chaining to// other class using super() keywordclass Base{ String name; // constructor 1 Base() { this(\"\"); System.out.println(\"No-argument constructor of\" + \" base class\"); } // constructor 2 Base(String name) { this.name = name; System.out.println(\"Calling parameterized constructor\" + \" of base\"); }} class Derived extends Base{ // constructor 3 Derived() { System.out.println(\"No-argument constructor \" + \"of derived\"); } // parameterized constructor 4 Derived(String name) { // invokes base class constructor 2 super(name); System.out.println(\"Calling parameterized \" + \"constructor of derived\"); } public static void main(String args[]) { // calls parameterized constructor 4 Derived obj = new Derived(\"test\"); // Calls No-argument constructor // Derived obj = new Derived(); }}",
"e": 34810,
"s": 33695,
"text": null
},
{
"code": null,
"e": 34819,
"s": 34810,
"text": "Output: "
},
{
"code": null,
"e": 34906,
"s": 34819,
"text": "Calling parameterized constructor of base\nCalling parameterized constructor of derived"
},
{
"code": null,
"e": 35365,
"s": 34906,
"text": "Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super class’s constructor are invoked before the sub class’s constructor.Alternative method : using Init block : When we want certain common resources to be executed with every constructor we can put the code in the init block. Init block is always executed before any constructor, whenever a constructor is used for creating a new object.Example 1:"
},
{
"code": null,
"e": 35370,
"s": 35365,
"text": "Java"
},
{
"code": "class Temp{ // block to be executed before any constructor. { System.out.println(\"init block\"); } // no-arg constructor Temp() { System.out.println(\"default\"); } // constructor with one argument. Temp(int x) { System.out.println(x); } public static void main(String[] args) { // Object creation by calling no-argument // constructor. new Temp(); // Object creation by calling parameterized // constructor with one parameter. new Temp(10); }}",
"e": 35921,
"s": 35370,
"text": null
},
{
"code": null,
"e": 35931,
"s": 35921,
"text": "Output: "
},
{
"code": null,
"e": 35964,
"s": 35931,
"text": "init block\ndefault\ninit block\n10"
},
{
"code": null,
"e": 36108,
"s": 35964,
"text": "NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same class. See the ex. Example : "
},
{
"code": null,
"e": 36113,
"s": 36108,
"text": "Java"
},
{
"code": "class Temp{ // block to be executed first { System.out.println(\"init\"); } Temp() { System.out.println(\"default\"); } Temp(int x) { System.out.println(x); } // block to be executed after the first block // which has been defined above. { System.out.println(\"second\"); } public static void main(String args[]) { new Temp(); new Temp(10); }}",
"e": 36542,
"s": 36113,
"text": null
},
{
"code": null,
"e": 36553,
"s": 36542,
"text": "Output : "
},
{
"code": null,
"e": 36588,
"s": 36553,
"text": "init\nsecond\ndefault\ninit\nsecond\n10"
},
{
"code": null,
"e": 37009,
"s": 36588,
"text": "This article is contributed by Apoorva singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 37018,
"s": 37009,
"text": "vkbvipul"
},
{
"code": null,
"e": 37039,
"s": 37018,
"text": "Vikramaditya Kukreja"
},
{
"code": null,
"e": 37050,
"s": 37039,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37062,
"s": 37050,
"text": "anikakapoor"
},
{
"code": null,
"e": 37072,
"s": 37062,
"text": "kalrap615"
},
{
"code": null,
"e": 37077,
"s": 37072,
"text": "Java"
},
{
"code": null,
"e": 37096,
"s": 37077,
"text": "School Programming"
},
{
"code": null,
"e": 37101,
"s": 37096,
"text": "Java"
},
{
"code": null,
"e": 37199,
"s": 37101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37243,
"s": 37199,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37258,
"s": 37243,
"text": "Stream In Java"
},
{
"code": null,
"e": 37283,
"s": 37258,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37319,
"s": 37283,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37350,
"s": 37319,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 37368,
"s": 37350,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37384,
"s": 37368,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37403,
"s": 37384,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 37428,
"s": 37403,
"text": "Reverse a string in Java"
}
]
|
How to use a variable for a key in a JavaScript object literal? - GeeksforGeeks | 31 Oct, 2019
In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines ‘ComputedPropertyName’ as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets.
Syntax:
var key="your_choice";
var object = {};
object[key] = "your_choice";
console.log(object);
Example 1: This shows how to use a variable for a key.
<html> <head> <title> How to use a variable for a key in a JavaScript object literal? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <script> var key = "Geeksforgeeks"; var object = {}; object[key] = "something"; console.log(object); </script></body> </html>
Output:
javascript-object
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 ?
How to Open URL in New Tab 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": 24778,
"s": 24750,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 25237,
"s": 24778,
"text": "In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines ‘ComputedPropertyName’ as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets."
},
{
"code": null,
"e": 25245,
"s": 25237,
"text": "Syntax:"
},
{
"code": null,
"e": 25335,
"s": 25245,
"text": "var key=\"your_choice\";\nvar object = {};\nobject[key] = \"your_choice\";\nconsole.log(object);"
},
{
"code": null,
"e": 25390,
"s": 25335,
"text": "Example 1: This shows how to use a variable for a key."
},
{
"code": "<html> <head> <title> How to use a variable for a key in a JavaScript object literal? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <script> var key = \"Geeksforgeeks\"; var object = {}; object[key] = \"something\"; console.log(object); </script></body> </html>",
"e": 25758,
"s": 25390,
"text": null
},
{
"code": null,
"e": 25766,
"s": 25758,
"text": "Output:"
},
{
"code": null,
"e": 25784,
"s": 25766,
"text": "javascript-object"
},
{
"code": null,
"e": 25791,
"s": 25784,
"text": "Picked"
},
{
"code": null,
"e": 25802,
"s": 25791,
"text": "JavaScript"
},
{
"code": null,
"e": 25819,
"s": 25802,
"text": "Web Technologies"
},
{
"code": null,
"e": 25917,
"s": 25819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25926,
"s": 25917,
"text": "Comments"
},
{
"code": null,
"e": 25939,
"s": 25926,
"text": "Old Comments"
},
{
"code": null,
"e": 25984,
"s": 25939,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26045,
"s": 25984,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26117,
"s": 26045,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26169,
"s": 26117,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26215,
"s": 26169,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26257,
"s": 26215,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26290,
"s": 26257,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26352,
"s": 26290,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26395,
"s": 26352,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Recursion in Scala - GeeksforGeeks | 29 Mar, 2019
Recursion is a method which breaks the problem into smaller sub problems and calls itself for each of the problems. That is, it simply means function calling itself. We can use recursion instead of loops. Recursion avoids mutable state associated with loops. Recursion is quite common in functional programming and provides a natural way to describe many Algorithms. Recursion is considered as to be important in functional programming. Scala supports Recursion very well.
Let us understand using the simple factorial example.Example :
// Scala program of factorial using recursion // Creating objectobject GFG{ // Function define def fact(n:Int): Int= { if(n == 1) 1 else n * fact(n - 1) } // Main method def main(args:Array[String]) { println(fact(3)) }}
Output:
6
The above code demonstrated in a recursive approach to a factorial function, where the condition n == 1 results in a break from the recursion.
Let us understand more clearly by an example of gcd.Example :
// Scala program of GCD using recursion // Creating objectobject GFG{ // Function defined def gcd(x:Int, y:Int): Int= { if (y == 0) x else gcd(y, x % y) } // Main method def main(args:Array[String]) { println(gcd(12, 18)) }}
Output:
6
Problem with recursion is that deep recursion can blow up the stack if we are not careful.Let’s understand this by using an example:Example Code:
// Scala program of sum all numbers// using recursion // Creating objectobject GFG{ // Function defined def sum(num: Int): Int= { if (num == 1) 1 else sum(num - 1) + num } // Main method def main(args:Array[String]) { println(sum(55)) }}
Output:
1540
The method sum will do the summation of all the numbers. We reduce the num everytime and add it to the result. Here, whenever we call sum, it will leave input value num on the stack and using up memory every time. when we try passing a large input like sum(555555) than the output will be java.lang.StackOverflowError. This output means that the stack has been blown up.
The above example does not use tail recursion and is therefore not an optimal approach, especially if the starting value n is very large.
The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.Let us understand it by a example:
Example :
// Scala program of factorial using tail recursionimport scala.annotation.tailrec // Creating objectobject GFG{ // Function defined def factorial(n: Int): Int = { // Using tail recursion @tailrec def factorialAcc(acc: Int, n: Int): Int = { if (n <= 1) acc else factorialAcc(n * acc, n - 1) } factorialAcc(1, n) } // Main method def main(args:Array[String]) { println(factorial(5)) }}
Output:
120
Here in the above code, we can use the @tailrec annotation to confirm that our algorithm is tail recursive.
If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error.
Example :
// Scala program of factorial with tail recursionimport scala.annotation.tailrec // Creating objectobject GFG{ // Function defined @tailrec def factorial(n: Int): Int = { if (n == 1) 1 else n * factorial(n - 1) } // Main method def main(args:Array[String]) { println(factorial(5)) }}
Output:
Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala List contains() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
How to get the first element of List in Scala | [
{
"code": null,
"e": 26173,
"s": 26145,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 26646,
"s": 26173,
"text": "Recursion is a method which breaks the problem into smaller sub problems and calls itself for each of the problems. That is, it simply means function calling itself. We can use recursion instead of loops. Recursion avoids mutable state associated with loops. Recursion is quite common in functional programming and provides a natural way to describe many Algorithms. Recursion is considered as to be important in functional programming. Scala supports Recursion very well."
},
{
"code": null,
"e": 26709,
"s": 26646,
"text": "Let us understand using the simple factorial example.Example :"
},
{
"code": "// Scala program of factorial using recursion // Creating objectobject GFG{ // Function define def fact(n:Int): Int= { if(n == 1) 1 else n * fact(n - 1) } // Main method def main(args:Array[String]) { println(fact(3)) }}",
"e": 26982,
"s": 26709,
"text": null
},
{
"code": null,
"e": 26990,
"s": 26982,
"text": "Output:"
},
{
"code": null,
"e": 26992,
"s": 26990,
"text": "6"
},
{
"code": null,
"e": 27135,
"s": 26992,
"text": "The above code demonstrated in a recursive approach to a factorial function, where the condition n == 1 results in a break from the recursion."
},
{
"code": null,
"e": 27197,
"s": 27135,
"text": "Let us understand more clearly by an example of gcd.Example :"
},
{
"code": "// Scala program of GCD using recursion // Creating objectobject GFG{ // Function defined def gcd(x:Int, y:Int): Int= { if (y == 0) x else gcd(y, x % y) } // Main method def main(args:Array[String]) { println(gcd(12, 18)) }}",
"e": 27474,
"s": 27197,
"text": null
},
{
"code": null,
"e": 27482,
"s": 27474,
"text": "Output:"
},
{
"code": null,
"e": 27484,
"s": 27482,
"text": "6"
},
{
"code": null,
"e": 27630,
"s": 27484,
"text": "Problem with recursion is that deep recursion can blow up the stack if we are not careful.Let’s understand this by using an example:Example Code:"
},
{
"code": "// Scala program of sum all numbers// using recursion // Creating objectobject GFG{ // Function defined def sum(num: Int): Int= { if (num == 1) 1 else sum(num - 1) + num } // Main method def main(args:Array[String]) { println(sum(55)) }}",
"e": 27943,
"s": 27630,
"text": null
},
{
"code": null,
"e": 27951,
"s": 27943,
"text": "Output:"
},
{
"code": null,
"e": 27956,
"s": 27951,
"text": "1540"
},
{
"code": null,
"e": 28327,
"s": 27956,
"text": "The method sum will do the summation of all the numbers. We reduce the num everytime and add it to the result. Here, whenever we call sum, it will leave input value num on the stack and using up memory every time. when we try passing a large input like sum(555555) than the output will be java.lang.StackOverflowError. This output means that the stack has been blown up."
},
{
"code": null,
"e": 28465,
"s": 28327,
"text": "The above example does not use tail recursion and is therefore not an optimal approach, especially if the starting value n is very large."
},
{
"code": null,
"e": 28795,
"s": 28465,
"text": "The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.Let us understand it by a example:"
},
{
"code": null,
"e": 28805,
"s": 28795,
"text": "Example :"
},
{
"code": "// Scala program of factorial using tail recursionimport scala.annotation.tailrec // Creating objectobject GFG{ // Function defined def factorial(n: Int): Int = { // Using tail recursion @tailrec def factorialAcc(acc: Int, n: Int): Int = { if (n <= 1) acc else factorialAcc(n * acc, n - 1) } factorialAcc(1, n) } // Main method def main(args:Array[String]) { println(factorial(5)) }}",
"e": 29315,
"s": 28805,
"text": null
},
{
"code": null,
"e": 29323,
"s": 29315,
"text": "Output:"
},
{
"code": null,
"e": 29327,
"s": 29323,
"text": "120"
},
{
"code": null,
"e": 29435,
"s": 29327,
"text": "Here in the above code, we can use the @tailrec annotation to confirm that our algorithm is tail recursive."
},
{
"code": null,
"e": 29672,
"s": 29435,
"text": "If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error."
},
{
"code": null,
"e": 29682,
"s": 29672,
"text": "Example :"
},
{
"code": "// Scala program of factorial with tail recursionimport scala.annotation.tailrec // Creating objectobject GFG{ // Function defined @tailrec def factorial(n: Int): Int = { if (n == 1) 1 else n * factorial(n - 1) } // Main method def main(args:Array[String]) { println(factorial(5)) }}",
"e": 30041,
"s": 29682,
"text": null
},
{
"code": null,
"e": 30049,
"s": 30041,
"text": "Output:"
},
{
"code": null,
"e": 30155,
"s": 30049,
"text": "Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position"
},
{
"code": null,
"e": 30162,
"s": 30155,
"text": "Picked"
},
{
"code": null,
"e": 30168,
"s": 30162,
"text": "Scala"
},
{
"code": null,
"e": 30181,
"s": 30168,
"text": "Scala-Method"
},
{
"code": null,
"e": 30187,
"s": 30181,
"text": "Scala"
},
{
"code": null,
"e": 30285,
"s": 30187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30303,
"s": 30285,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 30326,
"s": 30303,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 30347,
"s": 30326,
"text": "Scala | map() method"
},
{
"code": null,
"e": 30387,
"s": 30347,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 30413,
"s": 30387,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 30443,
"s": 30413,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 30465,
"s": 30443,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 30507,
"s": 30465,
"text": "Scala List contains() method with example"
},
{
"code": null,
"e": 30560,
"s": 30507,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
}
]
|
Program to find all types of Matrix - GeeksforGeeks | 13 Mar, 2022
Given the dimension of the matrix R(rows) * C(column) the task is to find which type of matrix is representing by the given dimension. Examples:
Input : R = 1 C = 0
Output : Row Matrix
Input : R = 4 C = 5
Output : Horizontal Matrix
Row Matrix : When R = 1 and C = 0 then the matrix represent Row Matrix .
Column Matrix : When C = 1 and R = 0 then the matrix represent Column Matrix.
Horizontal Matrix : A Matrix in which number of rows is smaller than the number of column is called Horizontal Matrix (R < C) .
Vertical Matrix : A Matrix in which number of rows is greater than the number of column is called Vertical Matrix (R > C).
Square Matrix : A matrix in which number of rows is equal to number of column is called Square Matrix (R = C).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check// types of Matrix#include <bits/stdc++.h>using namespace std; // Function to display which// type of matrixvoid check(int r, int c){ if (r == 0 && c == 1) cout << "Column Matrix " << endl; else if (r == 1 && c == 0) cout << "Row Matrix " << endl; else if (r < c) cout << "Horizontal Matrix " << endl; else if (r > c) cout << "Vertical Matrix " << endl; else if (r == c) cout << "Square Matrix " << endl;} // Driver codeint main(){ // input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); return 0;}
// Java program to check// types of Matriximport java.io.*;import java.util.*;import java.math.*;import java.util.regex.*; public class GFG { // Function to display which type of matrix static void check(int r, int c) { if (r == 0 && c == 1) System.out.println("Column Matrix "); else if (r == 1 && c == 0) System.out.println("Row Matrix "); else if (r < c) System.out.println("Horizontal Matrix "); else if (r > c) System.out.println("Vertical Matrix "); else if (r == c) System.out.println("Square Matrix "); } // Driver code public static void main(String[] args) { // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); }}
# Python3 program to check# types of Matrix # Function to display which# type of matrixdef check(r, c) : if r == 0 and c == 1: print ("Column Matrix ") elif r == 1 and c == 0: print ("Row Matrix ") elif r < c: print ("Horizontal Matrix ") elif r > c: print ("Vertical Matrix ") elif r == c: print ("Square Matrix ") # Driver codecheck(1, 0)check(0, 1)check(4, 5)check(5, 4)check(3, 3) # This code is contributed by Sam007.
// C# program to check types of Matrixusing System; class GFG{ // Function to display which type of matrix static void check(int r, int c) { if (r == 0 && c == 1) Console.WriteLine("Column Matrix "); else if (r == 1 && c == 0) Console.WriteLine("Row Matrix "); else if (r < c) Console.WriteLine("Horizontal Matrix "); else if (r > c) Console.WriteLine("Vertical Matrix "); else if (r == c) Console.WriteLine("Square Matrix "); } // Driver code static void Main() { // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); } } // This code is contributed by Sam007.
<?php// PHP program to check// types of Matrix // Function to display which// type of matrixfunction check($r, $c){ if ($r == 0 && $c == 1) echo "Column Matrix "."\n"; else if ($r == 1 && $c == 0) echo "Row Matrix "."\n"; else if ($r < $c) echo "Horizontal Matrix "."\n"; else if ($r > $c) echo "Vertical Matrix "."\n"; else if ($r == $c) echo "Square Matrix "."\n";} // Driver code // input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); // This code is contributed by Sam007?>
<script> // Javascript program to check types of Matrix // Function to display which type of matrix function check(r, c) { if (r == 0 && c == 1) document.write("Column Matrix " + "</br>"); else if (r == 1 && c == 0) document.write("Row Matrix " + "</br>"); else if (r < c) document.write("Horizontal Matrix " + "</br>"); else if (r > c) document.write("Vertical Matrix " + "</br>"); else if (r == c) document.write("Square Matrix " + "</br>"); } // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); </script>
Output :
Row Matrix
Column Matrix
Horizontal Matrix
Vertical Matrix
Square Matrix
Sam007
Akanksha_Rai
mukesh07
arshaim39
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flood fill Algorithm - how to implement fill() in paint?
Python program to add two Matrices
Program to find the Sum of each Row and each Column of a Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Multiplication of Matrix using threads
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24922,
"s": 24894,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 25069,
"s": 24922,
"text": "Given the dimension of the matrix R(rows) * C(column) the task is to find which type of matrix is representing by the given dimension. Examples: "
},
{
"code": null,
"e": 25159,
"s": 25069,
"text": "Input : R = 1 C = 0\nOutput : Row Matrix \n\nInput : R = 4 C = 5\nOutput : Horizontal Matrix "
},
{
"code": null,
"e": 25236,
"s": 25163,
"text": "Row Matrix : When R = 1 and C = 0 then the matrix represent Row Matrix ."
},
{
"code": null,
"e": 25314,
"s": 25236,
"text": "Column Matrix : When C = 1 and R = 0 then the matrix represent Column Matrix."
},
{
"code": null,
"e": 25442,
"s": 25314,
"text": "Horizontal Matrix : A Matrix in which number of rows is smaller than the number of column is called Horizontal Matrix (R < C) ."
},
{
"code": null,
"e": 25565,
"s": 25442,
"text": "Vertical Matrix : A Matrix in which number of rows is greater than the number of column is called Vertical Matrix (R > C)."
},
{
"code": null,
"e": 25676,
"s": 25565,
"text": "Square Matrix : A matrix in which number of rows is equal to number of column is called Square Matrix (R = C)."
},
{
"code": null,
"e": 25682,
"s": 25678,
"text": "C++"
},
{
"code": null,
"e": 25687,
"s": 25682,
"text": "Java"
},
{
"code": null,
"e": 25695,
"s": 25687,
"text": "Python3"
},
{
"code": null,
"e": 25698,
"s": 25695,
"text": "C#"
},
{
"code": null,
"e": 25702,
"s": 25698,
"text": "PHP"
},
{
"code": null,
"e": 25713,
"s": 25702,
"text": "Javascript"
},
{
"code": "// C++ program to check// types of Matrix#include <bits/stdc++.h>using namespace std; // Function to display which// type of matrixvoid check(int r, int c){ if (r == 0 && c == 1) cout << \"Column Matrix \" << endl; else if (r == 1 && c == 0) cout << \"Row Matrix \" << endl; else if (r < c) cout << \"Horizontal Matrix \" << endl; else if (r > c) cout << \"Vertical Matrix \" << endl; else if (r == c) cout << \"Square Matrix \" << endl;} // Driver codeint main(){ // input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); return 0;}",
"e": 26364,
"s": 25713,
"text": null
},
{
"code": "// Java program to check// types of Matriximport java.io.*;import java.util.*;import java.math.*;import java.util.regex.*; public class GFG { // Function to display which type of matrix static void check(int r, int c) { if (r == 0 && c == 1) System.out.println(\"Column Matrix \"); else if (r == 1 && c == 0) System.out.println(\"Row Matrix \"); else if (r < c) System.out.println(\"Horizontal Matrix \"); else if (r > c) System.out.println(\"Vertical Matrix \"); else if (r == c) System.out.println(\"Square Matrix \"); } // Driver code public static void main(String[] args) { // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); }}",
"e": 27215,
"s": 26364,
"text": null
},
{
"code": "# Python3 program to check# types of Matrix # Function to display which# type of matrixdef check(r, c) : if r == 0 and c == 1: print (\"Column Matrix \") elif r == 1 and c == 0: print (\"Row Matrix \") elif r < c: print (\"Horizontal Matrix \") elif r > c: print (\"Vertical Matrix \") elif r == c: print (\"Square Matrix \") # Driver codecheck(1, 0)check(0, 1)check(4, 5)check(5, 4)check(3, 3) # This code is contributed by Sam007. ",
"e": 27732,
"s": 27215,
"text": null
},
{
"code": "// C# program to check types of Matrixusing System; class GFG{ // Function to display which type of matrix static void check(int r, int c) { if (r == 0 && c == 1) Console.WriteLine(\"Column Matrix \"); else if (r == 1 && c == 0) Console.WriteLine(\"Row Matrix \"); else if (r < c) Console.WriteLine(\"Horizontal Matrix \"); else if (r > c) Console.WriteLine(\"Vertical Matrix \"); else if (r == c) Console.WriteLine(\"Square Matrix \"); } // Driver code static void Main() { // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); } } // This code is contributed by Sam007.",
"e": 28522,
"s": 27732,
"text": null
},
{
"code": "<?php// PHP program to check// types of Matrix // Function to display which// type of matrixfunction check($r, $c){ if ($r == 0 && $c == 1) echo \"Column Matrix \".\"\\n\"; else if ($r == 1 && $c == 0) echo \"Row Matrix \".\"\\n\"; else if ($r < $c) echo \"Horizontal Matrix \".\"\\n\"; else if ($r > $c) echo \"Vertical Matrix \".\"\\n\"; else if ($r == $c) echo \"Square Matrix \".\"\\n\";} // Driver code // input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); // This code is contributed by Sam007?>",
"e": 29135,
"s": 28522,
"text": null
},
{
"code": "<script> // Javascript program to check types of Matrix // Function to display which type of matrix function check(r, c) { if (r == 0 && c == 1) document.write(\"Column Matrix \" + \"</br>\"); else if (r == 1 && c == 0) document.write(\"Row Matrix \" + \"</br>\"); else if (r < c) document.write(\"Horizontal Matrix \" + \"</br>\"); else if (r > c) document.write(\"Vertical Matrix \" + \"</br>\"); else if (r == c) document.write(\"Square Matrix \" + \"</br>\"); } // static input for r and c // function calling check(1, 0); check(0, 1); check(4, 5); check(5, 4); check(3, 3); </script>",
"e": 29848,
"s": 29135,
"text": null
},
{
"code": null,
"e": 29859,
"s": 29848,
"text": "Output : "
},
{
"code": null,
"e": 29936,
"s": 29859,
"text": "Row Matrix \nColumn Matrix \nHorizontal Matrix \nVertical Matrix \nSquare Matrix"
},
{
"code": null,
"e": 29945,
"s": 29938,
"text": "Sam007"
},
{
"code": null,
"e": 29958,
"s": 29945,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29967,
"s": 29958,
"text": "mukesh07"
},
{
"code": null,
"e": 29977,
"s": 29967,
"text": "arshaim39"
},
{
"code": null,
"e": 29984,
"s": 29977,
"text": "Matrix"
},
{
"code": null,
"e": 30003,
"s": 29984,
"text": "School Programming"
},
{
"code": null,
"e": 30010,
"s": 30003,
"text": "Matrix"
},
{
"code": null,
"e": 30108,
"s": 30010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30117,
"s": 30108,
"text": "Comments"
},
{
"code": null,
"e": 30130,
"s": 30117,
"text": "Old Comments"
},
{
"code": null,
"e": 30187,
"s": 30130,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 30222,
"s": 30187,
"text": "Python program to add two Matrices"
},
{
"code": null,
"e": 30286,
"s": 30222,
"text": "Program to find the Sum of each Row and each Column of a Matrix"
},
{
"code": null,
"e": 30350,
"s": 30286,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 30389,
"s": 30350,
"text": "Multiplication of Matrix using threads"
},
{
"code": null,
"e": 30407,
"s": 30389,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30423,
"s": 30407,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30442,
"s": 30423,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30467,
"s": 30442,
"text": "Reverse a string in Java"
}
]
|
Number of Closed Islands in C++ | Suppose we have a 2D grid consists of 0s (as land) and 1s (as water). An island is a maximal 4- directionally connected group of 0s. A closed island is an island totally surrounded by 1s. We have to find the number of closed islands. So if the grid is like
So the output will be 2. There are two islands, that are completely surrounded by water.
To solve this, we will follow these steps −
Define a variable flag
Define a variable flag
Define a method called dfs, this will take the grid, i, j, n and m
Define a method called dfs, this will take the grid, i, j, n and m
if i and j are not inside the range of the grid, then set flag := false and return
if g[i,j] = 1 or g[i, j] = -1, then return
if g[i,j] = 1 or g[i, j] = -1, then return
if g[i, j] = 0, then g[i, j] = -1
if g[i, j] = 0, then g[i, j] = -1
call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)
call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)
The main method will be like −
The main method will be like −
create a dp matrix of order n x m, and fill it with -1
create a dp matrix of order n x m, and fill it with -1
for i in range 0 to n – 1for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
for i in range 0 to n – 1
for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
for j in range 0 to m – 1
if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
if g[i, j] = 0, then
flag := true
flag := true
dfs(g, i, j, n, m)
dfs(g, i, j, n, m)
flag := true
flag := true
ans := ans + flag
ans := ans + flag
return ans
return ans
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector < vector <int> > dp;
bool flag;
void dfs(vector<vector<int>>& g, int i, int j, int n, int m){
if(i>=n || j >=m || i<0 || j<0){
flag = false;
return ;
}
if(g[i][j] == 1 || g[i][j] == -1)return;
if(g[i][j] == 0)g[i][j] = -1;
dfs(g, i+1, j, n, m);
dfs(g, i, j+1, n, m);
dfs(g, i-1, j, n, m);
dfs(g,i, j-1, n, m);
}
int closedIsland(vector<vector<int>>& g) {
int ans = 0;
int n = g.size();
int m = g[0].size();
dp = vector < vector <int> > (n, vector <int> (m, -1));
for(int i = 0; i < n ; i++){
for(int j = 0; j < m; j++){
if(g[i][j] == 0){
flag = true;
dfs(g, i , j ,n ,m);
ans += flag;
}
}
}
return ans;
}
};
main(){
vector<vector<int>> v =
{{1,1,1,1,1,1,1,0},{1,0,0,0,0,1,1,0},{1,0,1,0,1,1,1,0},{1,0,0,0,0,1,0
,1},{1,1,1,1,1,1,1,0}};
Solution ob;
cout << (ob.closedIsland(v));
}
[[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
2 | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "Suppose we have a 2D grid consists of 0s (as land) and 1s (as water). An island is a maximal 4- directionally connected group of 0s. A closed island is an island totally surrounded by 1s. We have to find the number of closed islands. So if the grid is like"
},
{
"code": null,
"e": 1408,
"s": 1319,
"text": "So the output will be 2. There are two islands, that are completely surrounded by water."
},
{
"code": null,
"e": 1452,
"s": 1408,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1475,
"s": 1452,
"text": "Define a variable flag"
},
{
"code": null,
"e": 1498,
"s": 1475,
"text": "Define a variable flag"
},
{
"code": null,
"e": 1565,
"s": 1498,
"text": "Define a method called dfs, this will take the grid, i, j, n and m"
},
{
"code": null,
"e": 1632,
"s": 1565,
"text": "Define a method called dfs, this will take the grid, i, j, n and m"
},
{
"code": null,
"e": 1715,
"s": 1632,
"text": "if i and j are not inside the range of the grid, then set flag := false and return"
},
{
"code": null,
"e": 1758,
"s": 1715,
"text": "if g[i,j] = 1 or g[i, j] = -1, then return"
},
{
"code": null,
"e": 1801,
"s": 1758,
"text": "if g[i,j] = 1 or g[i, j] = -1, then return"
},
{
"code": null,
"e": 1835,
"s": 1801,
"text": "if g[i, j] = 0, then g[i, j] = -1"
},
{
"code": null,
"e": 1869,
"s": 1835,
"text": "if g[i, j] = 0, then g[i, j] = -1"
},
{
"code": null,
"e": 1965,
"s": 1869,
"text": "call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)"
},
{
"code": null,
"e": 2061,
"s": 1965,
"text": "call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)"
},
{
"code": null,
"e": 2092,
"s": 2061,
"text": "The main method will be like −"
},
{
"code": null,
"e": 2123,
"s": 2092,
"text": "The main method will be like −"
},
{
"code": null,
"e": 2178,
"s": 2123,
"text": "create a dp matrix of order n x m, and fill it with -1"
},
{
"code": null,
"e": 2233,
"s": 2178,
"text": "create a dp matrix of order n x m, and fill it with -1"
},
{
"code": null,
"e": 2363,
"s": 2233,
"text": "for i in range 0 to n – 1for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag"
},
{
"code": null,
"e": 2389,
"s": 2363,
"text": "for i in range 0 to n – 1"
},
{
"code": null,
"e": 2494,
"s": 2389,
"text": "for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag"
},
{
"code": null,
"e": 2520,
"s": 2494,
"text": "for j in range 0 to m – 1"
},
{
"code": null,
"e": 2600,
"s": 2520,
"text": "if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag"
},
{
"code": null,
"e": 2621,
"s": 2600,
"text": "if g[i, j] = 0, then"
},
{
"code": null,
"e": 2634,
"s": 2621,
"text": "flag := true"
},
{
"code": null,
"e": 2647,
"s": 2634,
"text": "flag := true"
},
{
"code": null,
"e": 2666,
"s": 2647,
"text": "dfs(g, i, j, n, m)"
},
{
"code": null,
"e": 2685,
"s": 2666,
"text": "dfs(g, i, j, n, m)"
},
{
"code": null,
"e": 2698,
"s": 2685,
"text": "flag := true"
},
{
"code": null,
"e": 2711,
"s": 2698,
"text": "flag := true"
},
{
"code": null,
"e": 2729,
"s": 2711,
"text": "ans := ans + flag"
},
{
"code": null,
"e": 2747,
"s": 2729,
"text": "ans := ans + flag"
},
{
"code": null,
"e": 2758,
"s": 2747,
"text": "return ans"
},
{
"code": null,
"e": 2769,
"s": 2758,
"text": "return ans"
},
{
"code": null,
"e": 2839,
"s": 2769,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2850,
"s": 2839,
"text": " Live Demo"
},
{
"code": null,
"e": 3935,
"s": 2850,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n vector < vector <int> > dp;\n bool flag;\n void dfs(vector<vector<int>>& g, int i, int j, int n, int m){\n if(i>=n || j >=m || i<0 || j<0){\n flag = false;\n return ;\n }\n if(g[i][j] == 1 || g[i][j] == -1)return;\n if(g[i][j] == 0)g[i][j] = -1;\n dfs(g, i+1, j, n, m);\n dfs(g, i, j+1, n, m);\n dfs(g, i-1, j, n, m);\n dfs(g,i, j-1, n, m);\n }\n int closedIsland(vector<vector<int>>& g) {\n int ans = 0;\n int n = g.size();\n int m = g[0].size();\n dp = vector < vector <int> > (n, vector <int> (m, -1));\n for(int i = 0; i < n ; i++){\n for(int j = 0; j < m; j++){\n if(g[i][j] == 0){\n flag = true;\n dfs(g, i , j ,n ,m);\n ans += flag;\n }\n }\n }\n return ans;\n }\n};\nmain(){\n vector<vector<int>> v =\n {{1,1,1,1,1,1,1,0},{1,0,0,0,0,1,1,0},{1,0,1,0,1,1,1,0},{1,0,0,0,0,1,0\n ,1},{1,1,1,1,1,1,1,0}};\n Solution ob;\n cout << (ob.closedIsland(v));\n}"
},
{
"code": null,
"e": 4027,
"s": 3935,
"text": "[[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]"
},
{
"code": null,
"e": 4029,
"s": 4027,
"text": "2"
}
]
|
p5.js | lights() Function - GeeksforGeeks | 13 Jan, 2022
The lights() function in p5.js is used to set the default ambient and directional light in the scene. The default ambient light used is ambientLight(128, 128, 128) and the directional light is directionalLight(128, 128, 128, 0, 0, -1). This function can be used to quickly add default lights in the scene.The lights() function has to be used in the draw() function of the code to remain persistent in the scene.Syntax:
lights()
Parameters: This function does not accept any parameters.Below examples illustrate the lights() function in p5.js:Example 1:
javascript
let newFont;let lightsEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); lightsEnableCheck = createCheckbox( "Enable Default Lights", false); lightsEnableCheck.position(20, 60); // Toggle default light lightsEnableCheck.changed(() => { lightsEnable = !lightsEnable; });} function draw() { background("green"); text("Click on the checkbox to toggle the" + " default lights.", -285, -125); noStroke(); shininess(15); specularMaterial(250); if (lightsEnable) { // Enable the default lights lights(); } sphere(80);}
Output:
Example 2:
javascript
let newFont;let lightsEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); lightsEnableCheck = createCheckbox( "Enable Default Lights", false); lightsEnableCheck.position(20, 60); // Toggle default light lightsEnableCheck.changed(() => { lightsEnable = !lightsEnable; });} function draw() { background("green"); text("Click on the checkbox to toggle the" + " default lights.", -285, -125); noStroke(); shininess(15); specularMaterial(250); if (lightsEnable) { // Enable the default lights lights(); } rotateX(millis() / 1000); rotateY(millis() / 1000); box(100);}
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/lights
adnanirshad158
JavaScript-p5.js
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24087,
"s": 24059,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 24508,
"s": 24087,
"text": "The lights() function in p5.js is used to set the default ambient and directional light in the scene. The default ambient light used is ambientLight(128, 128, 128) and the directional light is directionalLight(128, 128, 128, 0, 0, -1). This function can be used to quickly add default lights in the scene.The lights() function has to be used in the draw() function of the code to remain persistent in the scene.Syntax: "
},
{
"code": null,
"e": 24517,
"s": 24508,
"text": "lights()"
},
{
"code": null,
"e": 24643,
"s": 24517,
"text": "Parameters: This function does not accept any parameters.Below examples illustrate the lights() function in p5.js:Example 1: "
},
{
"code": null,
"e": 24654,
"s": 24643,
"text": "javascript"
},
{
"code": "let newFont;let lightsEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); lightsEnableCheck = createCheckbox( \"Enable Default Lights\", false); lightsEnableCheck.position(20, 60); // Toggle default light lightsEnableCheck.changed(() => { lightsEnable = !lightsEnable; });} function draw() { background(\"green\"); text(\"Click on the checkbox to toggle the\" + \" default lights.\", -285, -125); noStroke(); shininess(15); specularMaterial(250); if (lightsEnable) { // Enable the default lights lights(); } sphere(80);}",
"e": 25309,
"s": 24654,
"text": null
},
{
"code": null,
"e": 25319,
"s": 25309,
"text": "Output: "
},
{
"code": null,
"e": 25331,
"s": 25319,
"text": "Example 2: "
},
{
"code": null,
"e": 25342,
"s": 25331,
"text": "javascript"
},
{
"code": "let newFont;let lightsEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); lightsEnableCheck = createCheckbox( \"Enable Default Lights\", false); lightsEnableCheck.position(20, 60); // Toggle default light lightsEnableCheck.changed(() => { lightsEnable = !lightsEnable; });} function draw() { background(\"green\"); text(\"Click on the checkbox to toggle the\" + \" default lights.\", -285, -125); noStroke(); shininess(15); specularMaterial(250); if (lightsEnable) { // Enable the default lights lights(); } rotateX(millis() / 1000); rotateY(millis() / 1000); box(100);}",
"e": 26053,
"s": 25342,
"text": null
},
{
"code": null,
"e": 26063,
"s": 26053,
"text": "Output: "
},
{
"code": null,
"e": 26250,
"s": 26063,
"text": "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/lights "
},
{
"code": null,
"e": 26265,
"s": 26250,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26282,
"s": 26265,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 26293,
"s": 26282,
"text": "JavaScript"
},
{
"code": null,
"e": 26310,
"s": 26293,
"text": "Web Technologies"
},
{
"code": null,
"e": 26408,
"s": 26310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26417,
"s": 26408,
"text": "Comments"
},
{
"code": null,
"e": 26430,
"s": 26417,
"text": "Old Comments"
},
{
"code": null,
"e": 26491,
"s": 26430,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26536,
"s": 26491,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26608,
"s": 26536,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26660,
"s": 26608,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26706,
"s": 26660,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26762,
"s": 26706,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26795,
"s": 26762,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26857,
"s": 26795,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26900,
"s": 26857,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Logistic Regression — Idea and Application | by Tanveer Hurra | Towards Data Science | This article will try to:
Discuss the idea behind logistic regression
Explain it further through an example
What you are already supposed to know
Basic Probability Theory
Linear Regression
Sigmoid function
You are given a problem of predicting the gender of a person based on his/her height. To start with you are provided the data of 10 people, whose height and gender are known. You are asked to fit a mathematical model in this data in a way that will enable you to predict the gender of some other person whose height value is known but we have no information about his/her gender. This type of problem comes under the classification domain of supervised machine learning. If the problem demands from you to make classifications into various categories like True, False or rich, middle class, poor or Failure, Success, etc then you are dealing with the classification problems. Its counterpart in machine learning is a regression problem where the problem demands from us to predict a continuous value like marks = 33.4%, weight = 60 Kg, etc. This article will discuss a classification algorithm called Logistic regression.
Although there are a lot of classification algorithms out there that vary from each other in degree of complexity like Linear Discriminant Analysis, Decision Trees, Random Forest, etc, Logistic Regression is the most basic one and is perfect to learn about classification models. Let’s jump to the above-stated problem and suppose, we are given the data of ten people as shown below:
This problem is wholly different from other mathematical prediction problems. The reason being that, on one hand, we have continuous values of height but on the other hand, we have categorical values of gender. Our mathematical operations know how to deal with numbers but dealing with categorical values poses a challenge. To overcome this challenge in classification problems whether they are solved through logistic regression or some other algorithm, we always calculate the probability value associated with a class. In the given context, we will calculate the probability associated with the male class or female class. The probability with the other class need not be explicitly calculated but can be obtained by subtracting the probability of previously calculated class from one.
In the given data set, we have height as independent variable and gender as the dependent variable. For time being, if we assume it to be a regression problem, it would have been solved by calculating the parameters of the regression model given as below:
In short, we would have calculated Bo and B1 and problem solved. The classification problem cannot be solved in this manner. As stated, we cannot calculate the value of gender but the probability associated with a particular gender class. In logistic regression, we take inspiration from linear regression and use the linear model above to calculate probability. We just need a function that will take the above linear model as input and give us the probability value as output. In mathematical form, we should have something like this:
The above model calculates the probability of male class but we can use either of the two classes here. The function showed on the right side of the equation should satisfy the condition that it should take any real number input but should give the output in the range of 0 and 1 only, the reason being obvious. The above condition is satisfied by a function called Sigmoid or logistic function shown below:
The Sigmoid function has the domain of -inf to inf and the range of 0 to 1, which makes it perfect for probability calculation in logistic regression. If we plug the linear model in Sigmoid function we will get something as shown below:
The above equation can be easily rearranged to give us the more simple & easily understandable form as shown below:
The right-hand side of the equation is exactly what we have in the linear regression model & the left-hand side is the log of the probability of odds, also called logit. So the above equation can be also written as:
logit(gender=male) = Bo + B1*height
This is the idea behind the logistic regression. Now let’s solve the problem given to us to see its application.
We will use the Python code to train our model using the given data. Let’s first import the necessary modules. We need NumPy and LogisticRegression class from sklearn.
from sklearn.linear_model import LogisticRegression
So now modules are imported we need to create an instance of the LogisticRegression class.
lg = LogisticRegression(solver = ‘lbfgs’)
The solver used is lbfgs. It’s now time to create the data set that we will use to train the model.
height = np.array([[132,134,133,139,145,144,165,160,155,140]])gender = np.array([1,0,1,1,0,0,0,0,0,1])
Note that the sklearn can only handle numerical values, so here we are representing the female class with 1 and the male class with 0. Using the above datasets let’s train the model:
lg.fit(height.reshape(-1,1),gender.ravel())
Once the model is trained, you will get a confirmation message of the same. So no we have a trained model, let's check the parameters, the intercept ( Bo) and the slope( B1).
lg.coef_lg.intercept_
Running the above lines will show you the intercept value of 35.212 and the slope value of -0.252. Hence our trained model can be written as:
We can use the above equation to predict the gender of any person given his/her height or we can directly use the trained model as shown below to find the gender value of a person with say height = 140cm:
lg.predict(np.array([[140]]))
Give the above lines of code a try, you will get the idea. Note that the model actually gives us the probability value associated with a given class and it’s up to us to decide the threshold value of the probability. The default is considered 0.5 i.e. all the probability values associated with the male class above 0.5 are considered males & the probability of male class if less than 0.5 is considered female. Also, the separation boundary in logistic regression is linear which can be easily confirmed graphically.
Further Read
Linear Discriminant Analysis
Decision Trees
That is all in Logistic Regression. For any queries regarding the article, you can reach me on LinkedIn
Thanks,
Have a nice time 😊
Originally published at https://www.wildregressor.com on April 20, 2020. | [
{
"code": null,
"e": 198,
"s": 172,
"text": "This article will try to:"
},
{
"code": null,
"e": 242,
"s": 198,
"text": "Discuss the idea behind logistic regression"
},
{
"code": null,
"e": 280,
"s": 242,
"text": "Explain it further through an example"
},
{
"code": null,
"e": 318,
"s": 280,
"text": "What you are already supposed to know"
},
{
"code": null,
"e": 343,
"s": 318,
"text": "Basic Probability Theory"
},
{
"code": null,
"e": 361,
"s": 343,
"text": "Linear Regression"
},
{
"code": null,
"e": 378,
"s": 361,
"text": "Sigmoid function"
},
{
"code": null,
"e": 1300,
"s": 378,
"text": "You are given a problem of predicting the gender of a person based on his/her height. To start with you are provided the data of 10 people, whose height and gender are known. You are asked to fit a mathematical model in this data in a way that will enable you to predict the gender of some other person whose height value is known but we have no information about his/her gender. This type of problem comes under the classification domain of supervised machine learning. If the problem demands from you to make classifications into various categories like True, False or rich, middle class, poor or Failure, Success, etc then you are dealing with the classification problems. Its counterpart in machine learning is a regression problem where the problem demands from us to predict a continuous value like marks = 33.4%, weight = 60 Kg, etc. This article will discuss a classification algorithm called Logistic regression."
},
{
"code": null,
"e": 1684,
"s": 1300,
"text": "Although there are a lot of classification algorithms out there that vary from each other in degree of complexity like Linear Discriminant Analysis, Decision Trees, Random Forest, etc, Logistic Regression is the most basic one and is perfect to learn about classification models. Let’s jump to the above-stated problem and suppose, we are given the data of ten people as shown below:"
},
{
"code": null,
"e": 2473,
"s": 1684,
"text": "This problem is wholly different from other mathematical prediction problems. The reason being that, on one hand, we have continuous values of height but on the other hand, we have categorical values of gender. Our mathematical operations know how to deal with numbers but dealing with categorical values poses a challenge. To overcome this challenge in classification problems whether they are solved through logistic regression or some other algorithm, we always calculate the probability value associated with a class. In the given context, we will calculate the probability associated with the male class or female class. The probability with the other class need not be explicitly calculated but can be obtained by subtracting the probability of previously calculated class from one."
},
{
"code": null,
"e": 2729,
"s": 2473,
"text": "In the given data set, we have height as independent variable and gender as the dependent variable. For time being, if we assume it to be a regression problem, it would have been solved by calculating the parameters of the regression model given as below:"
},
{
"code": null,
"e": 3266,
"s": 2729,
"text": "In short, we would have calculated Bo and B1 and problem solved. The classification problem cannot be solved in this manner. As stated, we cannot calculate the value of gender but the probability associated with a particular gender class. In logistic regression, we take inspiration from linear regression and use the linear model above to calculate probability. We just need a function that will take the above linear model as input and give us the probability value as output. In mathematical form, we should have something like this:"
},
{
"code": null,
"e": 3674,
"s": 3266,
"text": "The above model calculates the probability of male class but we can use either of the two classes here. The function showed on the right side of the equation should satisfy the condition that it should take any real number input but should give the output in the range of 0 and 1 only, the reason being obvious. The above condition is satisfied by a function called Sigmoid or logistic function shown below:"
},
{
"code": null,
"e": 3911,
"s": 3674,
"text": "The Sigmoid function has the domain of -inf to inf and the range of 0 to 1, which makes it perfect for probability calculation in logistic regression. If we plug the linear model in Sigmoid function we will get something as shown below:"
},
{
"code": null,
"e": 4027,
"s": 3911,
"text": "The above equation can be easily rearranged to give us the more simple & easily understandable form as shown below:"
},
{
"code": null,
"e": 4243,
"s": 4027,
"text": "The right-hand side of the equation is exactly what we have in the linear regression model & the left-hand side is the log of the probability of odds, also called logit. So the above equation can be also written as:"
},
{
"code": null,
"e": 4279,
"s": 4243,
"text": "logit(gender=male) = Bo + B1*height"
},
{
"code": null,
"e": 4392,
"s": 4279,
"text": "This is the idea behind the logistic regression. Now let’s solve the problem given to us to see its application."
},
{
"code": null,
"e": 4560,
"s": 4392,
"text": "We will use the Python code to train our model using the given data. Let’s first import the necessary modules. We need NumPy and LogisticRegression class from sklearn."
},
{
"code": null,
"e": 4612,
"s": 4560,
"text": "from sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 4703,
"s": 4612,
"text": "So now modules are imported we need to create an instance of the LogisticRegression class."
},
{
"code": null,
"e": 4745,
"s": 4703,
"text": "lg = LogisticRegression(solver = ‘lbfgs’)"
},
{
"code": null,
"e": 4845,
"s": 4745,
"text": "The solver used is lbfgs. It’s now time to create the data set that we will use to train the model."
},
{
"code": null,
"e": 4948,
"s": 4845,
"text": "height = np.array([[132,134,133,139,145,144,165,160,155,140]])gender = np.array([1,0,1,1,0,0,0,0,0,1])"
},
{
"code": null,
"e": 5131,
"s": 4948,
"text": "Note that the sklearn can only handle numerical values, so here we are representing the female class with 1 and the male class with 0. Using the above datasets let’s train the model:"
},
{
"code": null,
"e": 5175,
"s": 5131,
"text": "lg.fit(height.reshape(-1,1),gender.ravel())"
},
{
"code": null,
"e": 5350,
"s": 5175,
"text": "Once the model is trained, you will get a confirmation message of the same. So no we have a trained model, let's check the parameters, the intercept ( Bo) and the slope( B1)."
},
{
"code": null,
"e": 5372,
"s": 5350,
"text": "lg.coef_lg.intercept_"
},
{
"code": null,
"e": 5514,
"s": 5372,
"text": "Running the above lines will show you the intercept value of 35.212 and the slope value of -0.252. Hence our trained model can be written as:"
},
{
"code": null,
"e": 5719,
"s": 5514,
"text": "We can use the above equation to predict the gender of any person given his/her height or we can directly use the trained model as shown below to find the gender value of a person with say height = 140cm:"
},
{
"code": null,
"e": 5749,
"s": 5719,
"text": "lg.predict(np.array([[140]]))"
},
{
"code": null,
"e": 6267,
"s": 5749,
"text": "Give the above lines of code a try, you will get the idea. Note that the model actually gives us the probability value associated with a given class and it’s up to us to decide the threshold value of the probability. The default is considered 0.5 i.e. all the probability values associated with the male class above 0.5 are considered males & the probability of male class if less than 0.5 is considered female. Also, the separation boundary in logistic regression is linear which can be easily confirmed graphically."
},
{
"code": null,
"e": 6280,
"s": 6267,
"text": "Further Read"
},
{
"code": null,
"e": 6309,
"s": 6280,
"text": "Linear Discriminant Analysis"
},
{
"code": null,
"e": 6324,
"s": 6309,
"text": "Decision Trees"
},
{
"code": null,
"e": 6428,
"s": 6324,
"text": "That is all in Logistic Regression. For any queries regarding the article, you can reach me on LinkedIn"
},
{
"code": null,
"e": 6436,
"s": 6428,
"text": "Thanks,"
},
{
"code": null,
"e": 6455,
"s": 6436,
"text": "Have a nice time 😊"
}
]
|
GATE | GATE-CS-2004 | Question 48 - GeeksforGeeks | 28 Jun, 2021
Consider two processes P1 and P2 accessing the shared variables X and Y protected by two binary semaphores SX and SY respectively, both initialized to 1. P and V denote the usual semaphone operators, where P decrements the semaphore value, and V increments the semaphore value. The pseudo-code of P1 and P2 is as follows :
P1 :
While true do {
L1 : ................
L2 : ................
X = X + 1;
Y = Y - 1;
V(SX);
V(SY);
}
P2 :
While true do {
L3 : ................
L4 : ................
Y = Y + 1;
X = Y - 1;
V(SY);
V(SX);
}
In order to avoid deadlock, the correct operators at L1, L2, L3 and L4 are respectively(A) P(SY), P(SX); P(SX), P(SY)(B) P(SX), P(SY); P(SY), P(SX)(C) P(SX), P(SX); P(SY), P(SY)(D) P(SX), P(SY); P(SX), P(SY)Answer: (D)Explanation:
Option A: In line L1 ( p(Sy) ) i.e. process p1 wants lock on Sy that is
held by process p2 and line L3 (p(Sx)) p2 wants lock on Sx which held by p1.
So here circular and wait condition exist means deadlock.
Option B : In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx that is held
by process p2 and line L3 (p(Sy)) p2 wants lock on Sx which held by p1. So here
circular and wait condition exist means deadlock.
Option C: In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx and line L3 (p(Sy))
p2 wants lock on Sx . But Sx and Sy can’t be released by its processes p1 and p2.
Please read the following to learn more about process synchronization and semaphores:Process Synchronization Set 1
This explanation has been contributed by Dheerendra Singh.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33 | [
{
"code": null,
"e": 24540,
"s": 24512,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24863,
"s": 24540,
"text": "Consider two processes P1 and P2 accessing the shared variables X and Y protected by two binary semaphores SX and SY respectively, both initialized to 1. P and V denote the usual semaphone operators, where P decrements the semaphore value, and V increments the semaphore value. The pseudo-code of P1 and P2 is as follows :"
},
{
"code": null,
"e": 24868,
"s": 24863,
"text": "P1 :"
},
{
"code": null,
"e": 24999,
"s": 24868,
"text": " While true do {\n L1 : ................\n L2 : ................\n X = X + 1;\n Y = Y - 1;\n V(SX);\n V(SY); \n }"
},
{
"code": null,
"e": 25004,
"s": 24999,
"text": "P2 :"
},
{
"code": null,
"e": 25136,
"s": 25004,
"text": " While true do {\n L3 : ................ \n L4 : ................\n Y = Y + 1;\n X = Y - 1;\n V(SY);\n V(SX); \n}"
},
{
"code": null,
"e": 25367,
"s": 25136,
"text": "In order to avoid deadlock, the correct operators at L1, L2, L3 and L4 are respectively(A) P(SY), P(SX); P(SX), P(SY)(B) P(SX), P(SY); P(SY), P(SX)(C) P(SX), P(SX); P(SY), P(SY)(D) P(SX), P(SY); P(SX), P(SY)Answer: (D)Explanation:"
},
{
"code": null,
"e": 25577,
"s": 25367,
"text": "Option A: In line L1 ( p(Sy) ) i.e. process p1 wants lock on Sy that is \nheld by process p2 and line L3 (p(Sx)) p2 wants lock on Sx which held by p1. \nSo here circular and wait condition exist means deadlock.\n"
},
{
"code": null,
"e": 25788,
"s": 25577,
"text": "Option B : In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx that is held \nby process p2 and line L3 (p(Sy)) p2 wants lock on Sx which held by p1. So here \ncircular and wait condition exist means deadlock.\n"
},
{
"code": null,
"e": 25956,
"s": 25788,
"text": "Option C: In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx and line L3 (p(Sy)) \np2 wants lock on Sx . But Sx and Sy can’t be released by its processes p1 and p2.\n"
},
{
"code": null,
"e": 26071,
"s": 25956,
"text": "Please read the following to learn more about process synchronization and semaphores:Process Synchronization Set 1"
},
{
"code": null,
"e": 26151,
"s": 26071,
"text": "This explanation has been contributed by Dheerendra Singh.Quiz of this Question"
},
{
"code": null,
"e": 26164,
"s": 26151,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 26182,
"s": 26164,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 26187,
"s": 26182,
"text": "GATE"
},
{
"code": null,
"e": 26285,
"s": 26187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26294,
"s": 26285,
"text": "Comments"
},
{
"code": null,
"e": 26307,
"s": 26294,
"text": "Old Comments"
},
{
"code": null,
"e": 26349,
"s": 26307,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26383,
"s": 26349,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26417,
"s": 26383,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26459,
"s": 26417,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26501,
"s": 26459,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26543,
"s": 26501,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 26577,
"s": 26543,
"text": "GATE | GATE-IT-2004 | Question 12"
},
{
"code": null,
"e": 26611,
"s": 26577,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 26653,
"s": 26611,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
}
]
|
Filter an array containing objects based on another array containing objects in JavaScript | Suppose we have two arrays of objects like these −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
We are required to write a JavaScript function that takes in two such arrays. Our function should return a new filtered version of the first array (arr1 in this case) that contains only those objects with a name property that are not contained in the second array (arr2 in this case) with the same name property.
Therefore, the output, in this case, should look like −
const output = [{id:'2',name:'B'},{id:'4',name:'D'}];
The code for this will be −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
const filterByReference = (arr1, arr2) => {
let res = [];
res = arr1.filter(el => {
return !arr2.find(element => {
return element.id === el.id;
});
});
return res;
}
console.log(filterByReference(arr1, arr2));
And the output in the console will be −
[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ] | [
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Suppose we have two arrays of objects like these −"
},
{
"code": null,
"e": 1285,
"s": 1113,
"text": "const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];\nconst arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];"
},
{
"code": null,
"e": 1598,
"s": 1285,
"text": "We are required to write a JavaScript function that takes in two such arrays. Our function should return a new filtered version of the first array (arr1 in this case) that contains only those objects with a name property that are not contained in the second array (arr2 in this case) with the same name property."
},
{
"code": null,
"e": 1654,
"s": 1598,
"text": "Therefore, the output, in this case, should look like −"
},
{
"code": null,
"e": 1708,
"s": 1654,
"text": "const output = [{id:'2',name:'B'},{id:'4',name:'D'}];"
},
{
"code": null,
"e": 1736,
"s": 1708,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2151,
"s": 1736,
"text": "const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];\nconst arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];\nconst filterByReference = (arr1, arr2) => {\n let res = [];\n res = arr1.filter(el => {\n return !arr2.find(element => {\n return element.id === el.id;\n });\n });\n return res;\n}\nconsole.log(filterByReference(arr1, arr2));"
},
{
"code": null,
"e": 2191,
"s": 2151,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2242,
"s": 2191,
"text": "[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]"
}
]
|
Stable Selection Sort | 29 Apr, 2021
A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.Any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal key or by tweaking it in a way such that its meaning doesn’t change and it becomes stable as well.Example :
Note: Subscripts are only used for understanding the concept.
Input : 4A 5 3 2 4B 1
Output : 1 2 3 4B 4A 5
Stable Selection Sort would have produced
Output : 1 2 3 4A 4B 5
Selection sort works by finding the minimum element and then inserting it in its correct position by swapping with the element which is in the position of this minimum element. This is what makes it unstable.Swapping might impact in pushing a key(let’s say A) to a position greater than the key(let’s say B) which are equal keys. which makes them out of desired order. In the above example 4A was pushed after 4B and after complete sorting this 4A remains after this 4B. Hence resulting in unstability.Selection sort can be made Stable if instead of swapping, the minimum element is placed in its position without swapping i.e. by placing the number in its position by pushing every element one step forward. In simple terms use a technique like insertion sort which means inserting element in its correct place. EXPLANATION WITH EXAMPLE:
Example: 4A 5 3 2 4B 1
First minimum element is 1, now instead
of swapping. Insert 1 in its correct place
and pushing every element one step forward
i.e forward pushing.
1 4A 5 3 2 4B
Next minimum is 2 :
1 2 4A 5 3 4B
Next minimum is 3 :
1 2 3 4A 5 4B
Repeat the steps until array is sorted.
1 2 3 4A 4B 5
C++
Java
Python3
C#
Javascript
// C++ program for modifying Selection Sort// so that it becomes stable.#include <iostream>using namespace std; void stableSelectionSort(int a[], int n){ // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till a[i - 1] // are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; }} void printArray(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl;} // Driver codeint main(){ int a[] = { 4, 5, 3, 2, 4, 1 }; int n = sizeof(a) / sizeof(a[0]); stableSelectionSort(a, n); printArray(a, n); return 0;}
// Java program for modifying Selection Sort// so that it becomes stable.class GFG{ static void stableSelectionSort(int[] a, int n) { // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) System.out.print(a[i]+ " "); System.out.println(); } // Driver code public static void main (String[] args) { int[] a = { 4, 5, 3, 2, 4, 1 }; int n = a.length; stableSelectionSort(a, n); printArray(a, n); }} // This code is contributed by Mr. Somesh Awasthi
# Python3 program for modifying Selection Sort# so that it becomes stable.def stableSelectionSort(a, n): # Traverse through all array elements for i in range(n): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i + 1, n): if a[min_idx] > a[j]: min_idx = j # Move minimum element at current i key = a[min_idx] while min_idx > i: a[min_idx] = a[min_idx - 1] min_idx -= 1 a[i] = key def printArray(a, n): for i in range(n): print("%d" %a[i], end = " ") # Driver Codea = [4, 5, 3, 2, 4, 1]n = len(a)stableSelectionSort(a, n)printArray(a, n) # This code is contributed# by Mr. Raju Pitta
// C# program for modifying Selection Sort// so that it becomes stable.using System; class GFG{ static void stableSelectionSort(int[] a, int n) { // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + " "); Console.WriteLine(); } // Driver code public static void Main () { int[] a = { 4, 5, 3, 2, 4, 1 }; int n = a.Length; stableSelectionSort(a, n); printArray(a, n); }} // This code is contributed by vt_m.
<script>// Javascript program for modifying Selection Sort// so that it becomes stable. function stableSelectionSort(a, n) { // Iterate through array elements for (let i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. let min = i; for (let j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. let key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } function prletArray(a, n) { for (let i = 0; i < n; i++) document.write(a[i]+ " "); document.write("<br/>"); } // driver function let a = [ 4, 5, 3, 2, 4, 1 ]; let n = a.length; stableSelectionSort(a, n); prletArray(a, n); </script>
Output:
1 2 3 4 4 5
This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
raju pitta
PrashanthPuneriya
sanjoy_62
Insertion Sort
selection-sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Segregate 0s and 1s in an array
Quickselect Algorithm
Sorting in Java
Quick Sort vs Merge Sort
Find whether an array is subset of another array
Stability in sorting algorithms | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 559,
"s": 52,
"text": "A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.Any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal key or by tweaking it in a way such that its meaning doesn’t change and it becomes stable as well.Example : "
},
{
"code": null,
"e": 733,
"s": 559,
"text": "Note: Subscripts are only used for understanding the concept.\n\nInput : 4A 5 3 2 4B 1\nOutput : 1 2 3 4B 4A 5\n\nStable Selection Sort would have produced\nOutput : 1 2 3 4A 4B 5"
},
{
"code": null,
"e": 1574,
"s": 733,
"text": "Selection sort works by finding the minimum element and then inserting it in its correct position by swapping with the element which is in the position of this minimum element. This is what makes it unstable.Swapping might impact in pushing a key(let’s say A) to a position greater than the key(let’s say B) which are equal keys. which makes them out of desired order. In the above example 4A was pushed after 4B and after complete sorting this 4A remains after this 4B. Hence resulting in unstability.Selection sort can be made Stable if instead of swapping, the minimum element is placed in its position without swapping i.e. by placing the number in its position by pushing every element one step forward. In simple terms use a technique like insertion sort which means inserting element in its correct place. EXPLANATION WITH EXAMPLE: "
},
{
"code": null,
"e": 1980,
"s": 1574,
"text": "Example: 4A 5 3 2 4B 1\n First minimum element is 1, now instead\n of swapping. Insert 1 in its correct place \n and pushing every element one step forward\n i.e forward pushing.\n 1 4A 5 3 2 4B\n Next minimum is 2 :\n 1 2 4A 5 3 4B\n Next minimum is 3 :\n 1 2 3 4A 5 4B\n Repeat the steps until array is sorted.\n 1 2 3 4A 4B 5"
},
{
"code": null,
"e": 1988,
"s": 1984,
"text": "C++"
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "Java"
},
{
"code": null,
"e": 2001,
"s": 1993,
"text": "Python3"
},
{
"code": null,
"e": 2004,
"s": 2001,
"text": "C#"
},
{
"code": null,
"e": 2015,
"s": 2004,
"text": "Javascript"
},
{
"code": "// C++ program for modifying Selection Sort// so that it becomes stable.#include <iostream>using namespace std; void stableSelectionSort(int a[], int n){ // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till a[i - 1] // are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; }} void printArray(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \" \"; cout << endl;} // Driver codeint main(){ int a[] = { 4, 5, 3, 2, 4, 1 }; int n = sizeof(a) / sizeof(a[0]); stableSelectionSort(a, n); printArray(a, n); return 0;}",
"e": 2969,
"s": 2015,
"text": null
},
{
"code": "// Java program for modifying Selection Sort// so that it becomes stable.class GFG{ static void stableSelectionSort(int[] a, int n) { // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) System.out.print(a[i]+ \" \"); System.out.println(); } // Driver code public static void main (String[] args) { int[] a = { 4, 5, 3, 2, 4, 1 }; int n = a.length; stableSelectionSort(a, n); printArray(a, n); }} // This code is contributed by Mr. Somesh Awasthi",
"e": 4141,
"s": 2969,
"text": null
},
{
"code": "# Python3 program for modifying Selection Sort# so that it becomes stable.def stableSelectionSort(a, n): # Traverse through all array elements for i in range(n): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i + 1, n): if a[min_idx] > a[j]: min_idx = j # Move minimum element at current i key = a[min_idx] while min_idx > i: a[min_idx] = a[min_idx - 1] min_idx -= 1 a[i] = key def printArray(a, n): for i in range(n): print(\"%d\" %a[i], end = \" \") # Driver Codea = [4, 5, 3, 2, 4, 1]n = len(a)stableSelectionSort(a, n)printArray(a, n) # This code is contributed# by Mr. Raju Pitta",
"e": 4890,
"s": 4141,
"text": null
},
{
"code": "// C# program for modifying Selection Sort// so that it becomes stable.using System; class GFG{ static void stableSelectionSort(int[] a, int n) { // Iterate through array elements for (int i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. int min = i; for (int j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. int key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); } // Driver code public static void Main () { int[] a = { 4, 5, 3, 2, 4, 1 }; int n = a.Length; stableSelectionSort(a, n); printArray(a, n); }} // This code is contributed by vt_m.",
"e": 6045,
"s": 4890,
"text": null
},
{
"code": "<script>// Javascript program for modifying Selection Sort// so that it becomes stable. function stableSelectionSort(a, n) { // Iterate through array elements for (let i = 0; i < n - 1; i++) { // Loop invariant : Elements till // a[i - 1] are already sorted. // Find minimum element from // arr[i] to arr[n - 1]. let min = i; for (let j = i + 1; j < n; j++) if (a[min] > a[j]) min = j; // Move minimum element at current i. let key = a[min]; while (min > i) { a[min] = a[min - 1]; min--; } a[i] = key; } } function prletArray(a, n) { for (let i = 0; i < n; i++) document.write(a[i]+ \" \"); document.write(\"<br/>\"); } // driver function let a = [ 4, 5, 3, 2, 4, 1 ]; let n = a.length; stableSelectionSort(a, n); prletArray(a, n); </script>",
"e": 7120,
"s": 6045,
"text": null
},
{
"code": null,
"e": 7130,
"s": 7120,
"text": "Output: "
},
{
"code": null,
"e": 7142,
"s": 7130,
"text": "1 2 3 4 4 5"
},
{
"code": null,
"e": 7562,
"s": 7142,
"text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7567,
"s": 7562,
"text": "vt_m"
},
{
"code": null,
"e": 7578,
"s": 7567,
"text": "raju pitta"
},
{
"code": null,
"e": 7596,
"s": 7578,
"text": "PrashanthPuneriya"
},
{
"code": null,
"e": 7606,
"s": 7596,
"text": "sanjoy_62"
},
{
"code": null,
"e": 7621,
"s": 7606,
"text": "Insertion Sort"
},
{
"code": null,
"e": 7636,
"s": 7621,
"text": "selection-sort"
},
{
"code": null,
"e": 7644,
"s": 7636,
"text": "Sorting"
},
{
"code": null,
"e": 7652,
"s": 7644,
"text": "Sorting"
},
{
"code": null,
"e": 7750,
"s": 7652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7781,
"s": 7750,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7817,
"s": 7781,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 7858,
"s": 7817,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 7953,
"s": 7858,
"text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements"
},
{
"code": null,
"e": 7985,
"s": 7953,
"text": "Segregate 0s and 1s in an array"
},
{
"code": null,
"e": 8007,
"s": 7985,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 8023,
"s": 8007,
"text": "Sorting in Java"
},
{
"code": null,
"e": 8048,
"s": 8023,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 8097,
"s": 8048,
"text": "Find whether an array is subset of another array"
}
]
|
What is conversion constructor in C++? | 01 Sep, 2021
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++
In C++, if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed.
Example
C++
#include <iostream> class MyClass { int a, b; public: MyClass(int i) { a = i; b = i; } void display() { std::cout << " a = " << a << " b = " << b << "\n"; }}; int main(){ MyClass object(10); object.display(); // Single parameter conversion constructor is invoked. object = 20; object.display(); return 0;}
Output:
a = 10 b = 10
a = 20 b = 20
Conversion Constructors: There are constructors that convert types of its parameter into a type of the class. The compiler uses these constructors to perform implicit class-type conversions. These conversions are made by invoking the corresponding constructor with matches the list of values/objects that are assigned to the object.
This previous example only deals with one parameter, to extend it to several parameters i.e., extended initializer lists or braced-init-lists. That is, we enclose the parameters to be passed to it inside a pair of curly braces ({}).
Example with Multiple Parameters:
C++
#include <iostream> class MyClass { int a, b; public: MyClass(int i, int y) { a = i; b = y; } void display() { std::cout << " a = " << a << " b = " << b << "\n"; }}; int main(){ MyClass object(10, 20); object.display(); // Multiple parameterized conversion constructor is invoked. object = { 30, 40 }; object.display(); return 0;}
Output:
a = 10 b = 20
a = 30 b = 40
Note:
Extended initializer lists are available in C++11 and on.We can directly try assigning a extended initializer list to a object when it is being created.An implicit class-type conversion feature of a constructor doesn’t affect its normal behavior.Using the explicit function-specifier for a constructor removes the implicit conversions using that constructor
Extended initializer lists are available in C++11 and on.
We can directly try assigning a extended initializer list to a object when it is being created.
An implicit class-type conversion feature of a constructor doesn’t affect its normal behavior.
Using the explicit function-specifier for a constructor removes the implicit conversions using that constructor
Usage of conversion constructor
1. In return value of a function:
When the return type of a function is a class, instead of returning a object, we can return a braced-init-list, now since the return type is a class instance, a object of that class is created with the braced-init-list, given that the class has a corresponding conversion constructor.
Example:
MyClass create_object(int x, int y) { return {x, y}; }
This function create_object will return a MyClass object with a and b values as the x and y passed to the function.
2. As a parameter to a function: When a function’s parameter type is of a class, instead of passing a object to the function, we can pass a braced-init-list to the function as the actual parameter, given that the class has a corresponding conversion constructor.
An example :
void display_object(MyClass obj) { obj.display(); }// This function is invoked in the main function with a braced-init-list with two integers as the parameter. // e.g. : // display_object({10, 20});
Note: This function display_object creates a new class instance of MyClass called obj and will call its member function display().
Credits: Bharath Vignesh J K
BharathVigneshJK
surindertarika1234
adnanirshad158
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 128,
"s": 54,
"text": "Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ "
},
{
"code": null,
"e": 350,
"s": 128,
"text": "In C++, if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed. "
},
{
"code": null,
"e": 360,
"s": 350,
"text": "Example "
},
{
"code": null,
"e": 364,
"s": 360,
"text": "C++"
},
{
"code": "#include <iostream> class MyClass { int a, b; public: MyClass(int i) { a = i; b = i; } void display() { std::cout << \" a = \" << a << \" b = \" << b << \"\\n\"; }}; int main(){ MyClass object(10); object.display(); // Single parameter conversion constructor is invoked. object = 20; object.display(); return 0;}",
"e": 731,
"s": 364,
"text": null
},
{
"code": null,
"e": 740,
"s": 731,
"text": "Output: "
},
{
"code": null,
"e": 768,
"s": 740,
"text": "a = 10 b = 10\na = 20 b = 20"
},
{
"code": null,
"e": 1101,
"s": 768,
"text": "Conversion Constructors: There are constructors that convert types of its parameter into a type of the class. The compiler uses these constructors to perform implicit class-type conversions. These conversions are made by invoking the corresponding constructor with matches the list of values/objects that are assigned to the object."
},
{
"code": null,
"e": 1334,
"s": 1101,
"text": "This previous example only deals with one parameter, to extend it to several parameters i.e., extended initializer lists or braced-init-lists. That is, we enclose the parameters to be passed to it inside a pair of curly braces ({})."
},
{
"code": null,
"e": 1369,
"s": 1334,
"text": "Example with Multiple Parameters: "
},
{
"code": null,
"e": 1373,
"s": 1369,
"text": "C++"
},
{
"code": "#include <iostream> class MyClass { int a, b; public: MyClass(int i, int y) { a = i; b = y; } void display() { std::cout << \" a = \" << a << \" b = \" << b << \"\\n\"; }}; int main(){ MyClass object(10, 20); object.display(); // Multiple parameterized conversion constructor is invoked. object = { 30, 40 }; object.display(); return 0;}",
"e": 1765,
"s": 1373,
"text": null
},
{
"code": null,
"e": 1774,
"s": 1765,
"text": "Output: "
},
{
"code": null,
"e": 1802,
"s": 1774,
"text": "a = 10 b = 20\na = 30 b = 40"
},
{
"code": null,
"e": 1810,
"s": 1802,
"text": "Note: "
},
{
"code": null,
"e": 2168,
"s": 1810,
"text": "Extended initializer lists are available in C++11 and on.We can directly try assigning a extended initializer list to a object when it is being created.An implicit class-type conversion feature of a constructor doesn’t affect its normal behavior.Using the explicit function-specifier for a constructor removes the implicit conversions using that constructor"
},
{
"code": null,
"e": 2226,
"s": 2168,
"text": "Extended initializer lists are available in C++11 and on."
},
{
"code": null,
"e": 2322,
"s": 2226,
"text": "We can directly try assigning a extended initializer list to a object when it is being created."
},
{
"code": null,
"e": 2417,
"s": 2322,
"text": "An implicit class-type conversion feature of a constructor doesn’t affect its normal behavior."
},
{
"code": null,
"e": 2529,
"s": 2417,
"text": "Using the explicit function-specifier for a constructor removes the implicit conversions using that constructor"
},
{
"code": null,
"e": 2563,
"s": 2529,
"text": "Usage of conversion constructor "
},
{
"code": null,
"e": 2598,
"s": 2563,
"text": "1. In return value of a function: "
},
{
"code": null,
"e": 2883,
"s": 2598,
"text": "When the return type of a function is a class, instead of returning a object, we can return a braced-init-list, now since the return type is a class instance, a object of that class is created with the braced-init-list, given that the class has a corresponding conversion constructor."
},
{
"code": null,
"e": 2894,
"s": 2883,
"text": "Example: "
},
{
"code": null,
"e": 2949,
"s": 2894,
"text": "MyClass create_object(int x, int y) { return {x, y}; }"
},
{
"code": null,
"e": 3066,
"s": 2949,
"text": "This function create_object will return a MyClass object with a and b values as the x and y passed to the function. "
},
{
"code": null,
"e": 3330,
"s": 3066,
"text": "2. As a parameter to a function: When a function’s parameter type is of a class, instead of passing a object to the function, we can pass a braced-init-list to the function as the actual parameter, given that the class has a corresponding conversion constructor. "
},
{
"code": null,
"e": 3345,
"s": 3330,
"text": "An example : "
},
{
"code": null,
"e": 3546,
"s": 3345,
"text": "void display_object(MyClass obj) { obj.display(); }// This function is invoked in the main function with a braced-init-list with two integers as the parameter. // e.g. : // display_object({10, 20}); "
},
{
"code": null,
"e": 3677,
"s": 3546,
"text": "Note: This function display_object creates a new class instance of MyClass called obj and will call its member function display()."
},
{
"code": null,
"e": 3706,
"s": 3677,
"text": "Credits: Bharath Vignesh J K"
},
{
"code": null,
"e": 3723,
"s": 3706,
"text": "BharathVigneshJK"
},
{
"code": null,
"e": 3742,
"s": 3723,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3757,
"s": 3742,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3761,
"s": 3757,
"text": "C++"
},
{
"code": null,
"e": 3765,
"s": 3761,
"text": "CPP"
}
]
|
Check if a string contains only alphabets in Java | 23 May, 2022
Given a string, the task is to write a Java program to check whether the string contains only alphabets or not. If so, then print true, otherwise false.
Examples:
Input: GeeksforGeeksOutput: trueExplanation: The given string contains only alphabets so the output is true.
Input: GeeksforGeeks2020Output: falseExplanation: The given string contains alphabets and numbers so the output is false.
Input: “”Output: falseExplanation: The given string is empty so the output is false.
Method 1: This problem can be solved using the ASCII values. Please refer this article for this approach.
Method 2: This problem can be solved using Lambda expression. Please refer this article for this approach.
Method 3: This problem can be solved using Regular Expression. Please refer this article for this approach.
Method 4: This approach uses the methods of Character class in Java
The idea is to iterate over each character of the string and check whether the specified character is a letter or not using Character.isLetter() method.
If the character is a letter then continue, else return false.
If we are able to iterate over the whole string, then return true.
Below is the implementation of the above approach:
Java
class GFG { // Function to check if a string // contains only alphabets public static boolean onlyAlphabets( String str, int n) { // Return false if the string // has empty or null if (str == null || str == "") { return false; } // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if the specified // character is not a letter then // return false, // else return true if (!Character .isLetter(str.charAt(i))) { return false; } } return true; } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksforGeeks"; int len = str.length(); // Function Call System.out.println( onlyAlphabets(str, len)); }}
true
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(1), no extra space required so it is a constant.
samim2000
Java-Character
java-lambda
java-regular-expression
Java-String-Programs
strings
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Write a program to reverse an array or string
C++ Data Types
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "Given a string, the task is to write a Java program to check whether the string contains only alphabets or not. If so, then print true, otherwise false."
},
{
"code": null,
"e": 191,
"s": 181,
"text": "Examples:"
},
{
"code": null,
"e": 300,
"s": 191,
"text": "Input: GeeksforGeeksOutput: trueExplanation: The given string contains only alphabets so the output is true."
},
{
"code": null,
"e": 422,
"s": 300,
"text": "Input: GeeksforGeeks2020Output: falseExplanation: The given string contains alphabets and numbers so the output is false."
},
{
"code": null,
"e": 507,
"s": 422,
"text": "Input: “”Output: falseExplanation: The given string is empty so the output is false."
},
{
"code": null,
"e": 613,
"s": 507,
"text": "Method 1: This problem can be solved using the ASCII values. Please refer this article for this approach."
},
{
"code": null,
"e": 720,
"s": 613,
"text": "Method 2: This problem can be solved using Lambda expression. Please refer this article for this approach."
},
{
"code": null,
"e": 828,
"s": 720,
"text": "Method 3: This problem can be solved using Regular Expression. Please refer this article for this approach."
},
{
"code": null,
"e": 896,
"s": 828,
"text": "Method 4: This approach uses the methods of Character class in Java"
},
{
"code": null,
"e": 1050,
"s": 896,
"text": "The idea is to iterate over each character of the string and check whether the specified character is a letter or not using Character.isLetter() method. "
},
{
"code": null,
"e": 1114,
"s": 1050,
"text": "If the character is a letter then continue, else return false. "
},
{
"code": null,
"e": 1181,
"s": 1114,
"text": "If we are able to iterate over the whole string, then return true."
},
{
"code": null,
"e": 1232,
"s": 1181,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1237,
"s": 1232,
"text": "Java"
},
{
"code": "class GFG { // Function to check if a string // contains only alphabets public static boolean onlyAlphabets( String str, int n) { // Return false if the string // has empty or null if (str == null || str == \"\") { return false; } // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if the specified // character is not a letter then // return false, // else return true if (!Character .isLetter(str.charAt(i))) { return false; } } return true; } // Driver Code public static void main(String args[]) { // Given string str String str = \"GeeksforGeeks\"; int len = str.length(); // Function Call System.out.println( onlyAlphabets(str, len)); }}",
"e": 2160,
"s": 1237,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2160,
"text": "true"
},
{
"code": null,
"e": 2229,
"s": 2165,
"text": "Time Complexity: O(N), where N is the size of the given string."
},
{
"code": null,
"e": 2297,
"s": 2229,
"text": "Auxiliary Space: O(1), no extra space required so it is a constant."
},
{
"code": null,
"e": 2307,
"s": 2297,
"text": "samim2000"
},
{
"code": null,
"e": 2322,
"s": 2307,
"text": "Java-Character"
},
{
"code": null,
"e": 2334,
"s": 2322,
"text": "java-lambda"
},
{
"code": null,
"e": 2358,
"s": 2334,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2379,
"s": 2358,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2387,
"s": 2379,
"text": "strings"
},
{
"code": null,
"e": 2392,
"s": 2387,
"text": "Java"
},
{
"code": null,
"e": 2400,
"s": 2392,
"text": "Strings"
},
{
"code": null,
"e": 2408,
"s": 2400,
"text": "Strings"
},
{
"code": null,
"e": 2413,
"s": 2408,
"text": "Java"
},
{
"code": null,
"e": 2511,
"s": 2413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2526,
"s": 2511,
"text": "Stream In Java"
},
{
"code": null,
"e": 2547,
"s": 2526,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2568,
"s": 2547,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2587,
"s": 2568,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2604,
"s": 2587,
"text": "Generics in Java"
},
{
"code": null,
"e": 2650,
"s": 2604,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 2665,
"s": 2650,
"text": "C++ Data Types"
},
{
"code": null,
"e": 2725,
"s": 2665,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 2759,
"s": 2725,
"text": "Longest Common Subsequence | DP-4"
}
]
|
How to pre populate database in Android using SQLite Database | 01 May, 2020
Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database.
Approach:
Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder.In activity_main.xml, add the following code.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingStart="5dp" android:paddingTop="5dp"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"/> </LinearLayout>Create a new custom_layout.xml file with the following code.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" > <TextView android:textStyle="bold" android:layout_margin="5dp" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView"/></LinearLayout>Create a DatabaseHelper class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = ""; private static String DB_NAME = "database.db"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = "algo_topics"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( "Error copying database"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e("message", "" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = "SELECT * FROM " + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}Create a MyAdapter.java class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}Finally, in MainActivity.java add the following code.package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}
Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}
dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}
Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder.
In activity_main.xml, add the following code.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingStart="5dp" android:paddingTop="5dp"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingStart="5dp" android:paddingTop="5dp"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical"/> </LinearLayout>
Create a new custom_layout.xml file with the following code.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" > <TextView android:textStyle="bold" android:layout_margin="5dp" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView"/></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" > <TextView android:textStyle="bold" android:layout_margin="5dp" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView"/></LinearLayout>
Create a DatabaseHelper class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = ""; private static String DB_NAME = "database.db"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = "algo_topics"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( "Error copying database"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e("message", "" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = "SELECT * FROM " + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}
package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = ""; private static String DB_NAME = "database.db"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = "algo_topics"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( "Error copying database"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e("message", "" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = "SELECT * FROM " + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}
Create a MyAdapter.java class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}
package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}
Finally, in MainActivity.java add the following code.package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}
package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}
Output:
android
DBMS
Java
Java
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 May, 2020"
},
{
"code": null,
"e": 342,
"s": 54,
"text": "Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database."
},
{
"code": null,
"e": 352,
"s": 342,
"text": "Approach:"
},
{
"code": null,
"e": 10658,
"s": 352,
"text": "Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder.In activity_main.xml, add the following code.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingStart=\"5dp\" android:paddingTop=\"5dp\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/my_recycler_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scrollbars=\"vertical\"/> </LinearLayout>Create a new custom_layout.xml file with the following code.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"3dp\" > <TextView android:textStyle=\"bold\" android:layout_margin=\"5dp\" android:textSize=\"20sp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/textView\"/></LinearLayout>Create a DatabaseHelper class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = \"\"; private static String DB_NAME = \"database.db\"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = \"algo_topics\"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( \"Error copying database\"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e(\"message\", \"\" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = \"SELECT * FROM \" + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}Create a MyAdapter.java class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}Finally, in MainActivity.java add the following code.package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}"
},
{
"code": null,
"e": 10843,
"s": 10658,
"text": "Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}"
},
{
"code": "dependencies{ implementation 'androidx.recyclerview:recyclerview:1.1.0'}",
"e": 10922,
"s": 10843,
"text": null
},
{
"code": null,
"e": 11111,
"s": 10922,
"text": "Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder."
},
{
"code": null,
"e": 11641,
"s": 11111,
"text": "In activity_main.xml, add the following code.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingStart=\"5dp\" android:paddingTop=\"5dp\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/my_recycler_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scrollbars=\"vertical\"/> </LinearLayout>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingStart=\"5dp\" android:paddingTop=\"5dp\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/my_recycler_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scrollbars=\"vertical\"/> </LinearLayout>",
"e": 12126,
"s": 11641,
"text": null
},
{
"code": null,
"e": 12667,
"s": 12126,
"text": "Create a new custom_layout.xml file with the following code.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"3dp\" > <TextView android:textStyle=\"bold\" android:layout_margin=\"5dp\" android:textSize=\"20sp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/textView\"/></LinearLayout>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"3dp\" > <TextView android:textStyle=\"bold\" android:layout_margin=\"5dp\" android:textSize=\"20sp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/textView\"/></LinearLayout>",
"e": 13148,
"s": 12667,
"text": null
},
{
"code": null,
"e": 18735,
"s": 13148,
"text": "Create a DatabaseHelper class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = \"\"; private static String DB_NAME = \"database.db\"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = \"algo_topics\"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( \"Error copying database\"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e(\"message\", \"\" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = \"SELECT * FROM \" + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}"
},
{
"code": "package org.geeksforgeeks.dictionary; import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // The Android's default system path // of your application database. private static String DB_PATH = \"\"; private static String DB_NAME = \"database.db\"; private SQLiteDatabase myDataBase; private final Context myContext; private SQLiteOpenHelper sqLiteOpenHelper; // Table name in the database. public static final String ALGO_TOPICS = \"algo_topics\"; /** * Constructor * Takes and keeps a reference of * the passed context in order * to access the application assets and resources. */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; DB_PATH = myContext.getDatabasePath(DB_NAME) .toString(); } // Creates an empty database // on the system and rewrites it // with your own database. public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and // the empty database will be // created into the default system // path of your application // so we are gonna be able // to overwrite that database // with our database. this.getWritableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error( \"Error copying database\"); } } } // Check if the database already exist // to avoid re-copying the file each // time you open the application // return true if it exists // false if it doesn't. private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH; checkDB = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.e(\"message\", \"\" + e); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your * local assets-folder to the just * created empty database in the * system folder, from where it * can be accessed and handled. * This is done by transferring bytestream. * */ private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets() .open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the // inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH; myDataBase = SQLiteDatabase .openDatabase( myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { // close the database. if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // It is an abstract method // but we define our own method here. } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // It is an abstract method which is // used to perform different task // based on the version of database. } // This method is used to get the // algorithm topics from the database. public List<String> getAlgorithmTopics( Activity activity) { sqLiteOpenHelper = new DatabaseHelper(activity); SQLiteDatabase db = sqLiteOpenHelper .getWritableDatabase(); List<String> list = new ArrayList<>(); // query help us to return all data // the present in the ALGO_TOPICS table. String query = \"SELECT * FROM \" + ALGO_TOPICS; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { list.add(cursor.getString(1)); } while (cursor.moveToNext()); } return list; }}",
"e": 24265,
"s": 18735,
"text": null
},
{
"code": null,
"e": 25897,
"s": 24265,
"text": "Create a MyAdapter.java class and add the following code.package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}"
},
{
"code": "package org.geeksforgeeks.dictionary; import android.app.Activity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.List; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private List<String> data; Activity activity; public MyAdapter(Activity activity, List<String> data) { this.data = data; this.activity = activity; } // This method is used to attach // custom layout to the recycler view @NonNull @Override public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { LayoutInflater LI = activity.getLayoutInflater(); View vw = LI.inflate( R.layout.custom_layout, null); return new ViewHolder(vw); } // This method is used to set the action // to the widgets of our custom layout. @Override public void onBindViewHolder( @NonNull ViewHolder holder, int position) { holder.topic_name .setText(data.get(position)); } @Override public int getItemCount() { return data.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView topic_name; public ViewHolder(View itemView) { super(itemView); this.topic_name = itemView.findViewById(R.id.textView); } }}",
"e": 27472,
"s": 25897,
"text": null
},
{
"code": null,
"e": 29120,
"s": 27472,
"text": "Finally, in MainActivity.java add the following code.package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}"
},
{
"code": "package org.geeksforgeeks.algorithmTopics; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.DefaultItemAnimator;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { private static RecyclerView.Adapter adapter; private static RecyclerView recyclerView; public static List<String> data; DatabaseHelper db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.my_recycler_view); db = new DatabaseHelper(this); recyclerView.setLayoutManager( new LinearLayoutManager(this)); data = new ArrayList<>(); fetchData(); } public void fetchData() { // Before fetching the data // directly from the database. // first we have to creates an empty // database on the system and // rewrites it with your own database. // Then we have to open the // database to fetch the data from it. db = new DatabaseHelper(this); try { db.createDataBase(); db.openDataBase(); } catch (Exception e) { e.printStackTrace(); } data = db.getAlgorithmTopics(this); adapter = new MyAdapter(this, data); recyclerView.setAdapter(adapter); }}",
"e": 30715,
"s": 29120,
"text": null
},
{
"code": null,
"e": 30723,
"s": 30715,
"text": "Output:"
},
{
"code": null,
"e": 30731,
"s": 30723,
"text": "android"
},
{
"code": null,
"e": 30736,
"s": 30731,
"text": "DBMS"
},
{
"code": null,
"e": 30741,
"s": 30736,
"text": "Java"
},
{
"code": null,
"e": 30746,
"s": 30741,
"text": "Java"
},
{
"code": null,
"e": 30751,
"s": 30746,
"text": "DBMS"
}
]
|
Stack.Synchronized() Method in C# | 04 Feb, 2019
This method(comes under System.Collections Namespace) is used to return a synchronized (thread safe) wrapper for the Stack. To guarantee the thread safety of the Stack, all operations must be done through this wrapper.
Syntax:
public static System.Collections.Stack Synchronized (System.Collections.Stack stack);
Return Value: It returns synchronized wrapper around the Stack.
Exception: This method will give ArgumentNullException if the stack is null.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Creates a synchronized // wrapper around the Stack Stack st = Stack.Synchronized(myStack); // Displays the synchronization // status of both Stack Console.WriteLine("myStack is {0}.", myStack.IsSynchronized ? "Synchronized" : "Not Synchronized"); Console.WriteLine("st is {0}.", st.IsSynchronized ? "Synchronized" : "Not Synchronized"); }}
Output:
myStack is Not Synchronized.
st is Synchronized.
Example 2:
// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("C"); myStack.Push("C++"); myStack.Push("Java"); myStack.Push("C#"); myStack.Push("Python"); // it will give error as // the parameter is null Stack sq = Stack.Synchronized(null); }}
Runtime Error:
Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: stack
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.synchronized?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Feb, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "This method(comes under System.Collections Namespace) is used to return a synchronized (thread safe) wrapper for the Stack. To guarantee the thread safety of the Stack, all operations must be done through this wrapper."
},
{
"code": null,
"e": 255,
"s": 247,
"text": "Syntax:"
},
{
"code": null,
"e": 341,
"s": 255,
"text": "public static System.Collections.Stack Synchronized (System.Collections.Stack stack);"
},
{
"code": null,
"e": 405,
"s": 341,
"text": "Return Value: It returns synchronized wrapper around the Stack."
},
{
"code": null,
"e": 482,
"s": 405,
"text": "Exception: This method will give ArgumentNullException if the stack is null."
},
{
"code": null,
"e": 543,
"s": 482,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 554,
"s": 543,
"text": "Example 1:"
},
{
"code": "// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Creates a synchronized // wrapper around the Stack Stack st = Stack.Synchronized(myStack); // Displays the synchronization // status of both Stack Console.WriteLine(\"myStack is {0}.\", myStack.IsSynchronized ? \"Synchronized\" : \"Not Synchronized\"); Console.WriteLine(\"st is {0}.\", st.IsSynchronized ? \"Synchronized\" : \"Not Synchronized\"); }}",
"e": 1463,
"s": 554,
"text": null
},
{
"code": null,
"e": 1471,
"s": 1463,
"text": "Output:"
},
{
"code": null,
"e": 1521,
"s": 1471,
"text": "myStack is Not Synchronized.\nst is Synchronized.\n"
},
{
"code": null,
"e": 1532,
"s": 1521,
"text": "Example 2:"
},
{
"code": "// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"C\"); myStack.Push(\"C++\"); myStack.Push(\"Java\"); myStack.Push(\"C#\"); myStack.Push(\"Python\"); // it will give error as // the parameter is null Stack sq = Stack.Synchronized(null); }}",
"e": 2068,
"s": 1532,
"text": null
},
{
"code": null,
"e": 2083,
"s": 2068,
"text": "Runtime Error:"
},
{
"code": null,
"e": 2176,
"s": 2083,
"text": "Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: stack"
},
{
"code": null,
"e": 2187,
"s": 2176,
"text": "Reference:"
},
{
"code": null,
"e": 2293,
"s": 2187,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.synchronized?view=netframework-4.7.2"
},
{
"code": null,
"e": 2322,
"s": 2293,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2347,
"s": 2322,
"text": "CSharp-Collections-Stack"
},
{
"code": null,
"e": 2361,
"s": 2347,
"text": "CSharp-method"
},
{
"code": null,
"e": 2364,
"s": 2361,
"text": "C#"
}
]
|
Number of visible boxes after putting one inside another | 06 May, 2021
Given N boxes and their size in an array. You are allowed to keep a box inside another box only if the box in which it is held is empty and the size of the box is at least twice as large as the size of the box. The task is to find minimum number of visible boxes.Examples –
Input : arr[] = { 1, 3, 4, 5 }
Output : 3
Put box of size 1 in box of size 3.
Input : arr[] = { 4, 2, 1, 8 }
Output : 1
Put box of size 1 in box of size 2
and box of size 2 in box of size 4.
And put box of size 4 in box of size 8.
The idea is to sort the array. Now, make a queue and insert first element of sorted array. Now traverse the array from first element and insert each element in the queue, also check if front element of queue is less than or equal to half of current traversed element. So, the number of visible box will be number of element in queue after traversing the sorted array. Basically, we are trying to put a box of size in smallest box which is greater than or equal to 2*x. For example, if arr[] = { 2, 3, 4, 6 }, then we try to put box of size 2 in box of size 4 instead of box of size 6 because if we put box of size 2 in box of size 6 then box of size 3 cannot be kept in any other box and we need to minimize the number of visible box.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count number of visible boxes.#include <bits/stdc++.h>using namespace std; // return the minimum number of visible boxesint minimumBox(int arr[], int n){ queue<int> q; // sorting the array sort(arr, arr + n); q.push(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.front(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.pop(); // Pushing each element of array q.push(arr[i]); } return q.size();} // driver Programint main(){ int arr[] = { 4, 1, 2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumBox(arr, n) << endl; return 0;}
// Java program to count number of visible// boxes. import java.util.LinkedList;import java.util.Queue;import java.util.Arrays; public class GFG { // return the minimum number of visible // boxes static int minimumBox(int []arr, int n) { // New Queue of integers. Queue<Integer> q = new LinkedList<>(); // sorting the array Arrays.sort(arr); q.add(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.element(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.remove(); // Pushing each element of array q.add(arr[i]); } return q.size(); } // Driver code public static void main(String args[]) { int [] arr = { 4, 1, 2, 8 }; int n = arr.length; System.out.println(minimumBox(arr, n)); }} // This code is contributed by Sam007.
# Python3 program to count number# of visible boxes. import collections # return the minimum number of visible boxesdef minimumBox(arr, n): q = collections.deque([]) # sorting the array arr.sort() q.append(arr[0]) # traversing the array for i in range(1, n): now = q[0] # checking if current element # is greater than or equal to # twice of front element if(arr[i] >= 2 * now): q.popleft() # Pushing each element of array q.append(arr[i]) return len(q) # driver Programif __name__=='__main__': arr = [4, 1, 2, 8 ] n = len(arr) print(minimumBox(arr, n)) # This code is contributed by# Sanjit_Prasad
// C# program to count number of visible// boxes.using System;using System.Collections.Generic; class GFG { // return the minimum number of visible // boxes static int minimumBox(int []arr, int n) { // New Queue of integers. Queue<int> q = new Queue<int>(); // sorting the array Array.Sort(arr); q.Enqueue(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.Peek(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.Dequeue(); // Pushing each element of array q.Enqueue(arr[i]); } return q.Count; } // Driver code public static void Main() { int [] arr = { 4, 1, 2, 8 }; int n = arr.Length; Console.WriteLine(minimumBox(arr, n)); }} // This code is contributed by Sam007.
<?php// PHP program to count number of visible boxes. // return the minimum number of visible boxesfunction minimumBox($arr, $n){ $q = array(); // sorting the array sort($arr); array_push($q, $arr[0]); // traversing the array for ($i = 1; $i < $n; $i++) { $now = $q[0]; // checking if current element // is greater than or equal to // twice of front element if ($arr[$i] >= 2 * $now) array_pop($q); // Pushing each element of array array_push($q,$arr[$i]); } return count($q);} // Driver Code$arr = array( 4, 1, 2, 8 );$n = count($arr);echo minimumBox($arr, $n); // This code is contributed by mits?>
<script> // Javascript program to count// number of visible boxes. // return the minimum number// of visible boxesfunction minimumBox(arr, n){ var q = []; // sorting the array arr.sort((a,b)=> a-b) q.push(arr[0]); // traversing the array for (var i = 1; i < n; i++) { var now = q[0]; // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.pop(0); // Pushing each element of array q.push(arr[i]); } return q.length;} // driver Programvar arr = [ 4, 1, 2, 8 ];var n = arr.length;document.write( minimumBox(arr, n)); </script>
Output:
1
Time Complexity: O(nlogn)
Sam007
Sanjit_Prasad
Mithun Kumar
noob2000
cpp-queue
Arrays
Mathematical
Sorting
Arrays
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 330,
"s": 54,
"text": "Given N boxes and their size in an array. You are allowed to keep a box inside another box only if the box in which it is held is empty and the size of the box is at least twice as large as the size of the box. The task is to find minimum number of visible boxes.Examples – "
},
{
"code": null,
"e": 563,
"s": 330,
"text": "Input : arr[] = { 1, 3, 4, 5 }\nOutput : 3\nPut box of size 1 in box of size 3.\n\nInput : arr[] = { 4, 2, 1, 8 }\nOutput : 1\nPut box of size 1 in box of size 2 \nand box of size 2 in box of size 4.\nAnd put box of size 4 in box of size 8."
},
{
"code": null,
"e": 1302,
"s": 565,
"text": "The idea is to sort the array. Now, make a queue and insert first element of sorted array. Now traverse the array from first element and insert each element in the queue, also check if front element of queue is less than or equal to half of current traversed element. So, the number of visible box will be number of element in queue after traversing the sorted array. Basically, we are trying to put a box of size in smallest box which is greater than or equal to 2*x. For example, if arr[] = { 2, 3, 4, 6 }, then we try to put box of size 2 in box of size 4 instead of box of size 6 because if we put box of size 2 in box of size 6 then box of size 3 cannot be kept in any other box and we need to minimize the number of visible box. "
},
{
"code": null,
"e": 1306,
"s": 1302,
"text": "C++"
},
{
"code": null,
"e": 1311,
"s": 1306,
"text": "Java"
},
{
"code": null,
"e": 1319,
"s": 1311,
"text": "Python3"
},
{
"code": null,
"e": 1322,
"s": 1319,
"text": "C#"
},
{
"code": null,
"e": 1326,
"s": 1322,
"text": "PHP"
},
{
"code": null,
"e": 1337,
"s": 1326,
"text": "Javascript"
},
{
"code": "// CPP program to count number of visible boxes.#include <bits/stdc++.h>using namespace std; // return the minimum number of visible boxesint minimumBox(int arr[], int n){ queue<int> q; // sorting the array sort(arr, arr + n); q.push(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.front(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.pop(); // Pushing each element of array q.push(arr[i]); } return q.size();} // driver Programint main(){ int arr[] = { 4, 1, 2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumBox(arr, n) << endl; return 0;}",
"e": 2090,
"s": 1337,
"text": null
},
{
"code": "// Java program to count number of visible// boxes. import java.util.LinkedList;import java.util.Queue;import java.util.Arrays; public class GFG { // return the minimum number of visible // boxes static int minimumBox(int []arr, int n) { // New Queue of integers. Queue<Integer> q = new LinkedList<>(); // sorting the array Arrays.sort(arr); q.add(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.element(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.remove(); // Pushing each element of array q.add(arr[i]); } return q.size(); } // Driver code public static void main(String args[]) { int [] arr = { 4, 1, 2, 8 }; int n = arr.length; System.out.println(minimumBox(arr, n)); }} // This code is contributed by Sam007.",
"e": 3171,
"s": 2090,
"text": null
},
{
"code": "# Python3 program to count number# of visible boxes. import collections # return the minimum number of visible boxesdef minimumBox(arr, n): q = collections.deque([]) # sorting the array arr.sort() q.append(arr[0]) # traversing the array for i in range(1, n): now = q[0] # checking if current element # is greater than or equal to # twice of front element if(arr[i] >= 2 * now): q.popleft() # Pushing each element of array q.append(arr[i]) return len(q) # driver Programif __name__=='__main__': arr = [4, 1, 2, 8 ] n = len(arr) print(minimumBox(arr, n)) # This code is contributed by# Sanjit_Prasad",
"e": 3867,
"s": 3171,
"text": null
},
{
"code": "// C# program to count number of visible// boxes.using System;using System.Collections.Generic; class GFG { // return the minimum number of visible // boxes static int minimumBox(int []arr, int n) { // New Queue of integers. Queue<int> q = new Queue<int>(); // sorting the array Array.Sort(arr); q.Enqueue(arr[0]); // traversing the array for (int i = 1; i < n; i++) { int now = q.Peek(); // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.Dequeue(); // Pushing each element of array q.Enqueue(arr[i]); } return q.Count; } // Driver code public static void Main() { int [] arr = { 4, 1, 2, 8 }; int n = arr.Length; Console.WriteLine(minimumBox(arr, n)); }} // This code is contributed by Sam007.",
"e": 4889,
"s": 3867,
"text": null
},
{
"code": "<?php// PHP program to count number of visible boxes. // return the minimum number of visible boxesfunction minimumBox($arr, $n){ $q = array(); // sorting the array sort($arr); array_push($q, $arr[0]); // traversing the array for ($i = 1; $i < $n; $i++) { $now = $q[0]; // checking if current element // is greater than or equal to // twice of front element if ($arr[$i] >= 2 * $now) array_pop($q); // Pushing each element of array array_push($q,$arr[$i]); } return count($q);} // Driver Code$arr = array( 4, 1, 2, 8 );$n = count($arr);echo minimumBox($arr, $n); // This code is contributed by mits?>",
"e": 5584,
"s": 4889,
"text": null
},
{
"code": "<script> // Javascript program to count// number of visible boxes. // return the minimum number// of visible boxesfunction minimumBox(arr, n){ var q = []; // sorting the array arr.sort((a,b)=> a-b) q.push(arr[0]); // traversing the array for (var i = 1; i < n; i++) { var now = q[0]; // checking if current element // is greater than or equal to // twice of front element if (arr[i] >= 2 * now) q.pop(0); // Pushing each element of array q.push(arr[i]); } return q.length;} // driver Programvar arr = [ 4, 1, 2, 8 ];var n = arr.length;document.write( minimumBox(arr, n)); </script>",
"e": 6259,
"s": 5584,
"text": null
},
{
"code": null,
"e": 6268,
"s": 6259,
"text": "Output: "
},
{
"code": null,
"e": 6270,
"s": 6268,
"text": "1"
},
{
"code": null,
"e": 6297,
"s": 6270,
"text": "Time Complexity: O(nlogn) "
},
{
"code": null,
"e": 6304,
"s": 6297,
"text": "Sam007"
},
{
"code": null,
"e": 6318,
"s": 6304,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 6331,
"s": 6318,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6340,
"s": 6331,
"text": "noob2000"
},
{
"code": null,
"e": 6350,
"s": 6340,
"text": "cpp-queue"
},
{
"code": null,
"e": 6357,
"s": 6350,
"text": "Arrays"
},
{
"code": null,
"e": 6370,
"s": 6357,
"text": "Mathematical"
},
{
"code": null,
"e": 6378,
"s": 6370,
"text": "Sorting"
},
{
"code": null,
"e": 6385,
"s": 6378,
"text": "Arrays"
},
{
"code": null,
"e": 6398,
"s": 6385,
"text": "Mathematical"
},
{
"code": null,
"e": 6406,
"s": 6398,
"text": "Sorting"
}
]
|
Scala Lists | 14 Mar, 2019
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items.Following are the point of difference between lists and array in Scala:
Lists are immutable whereas arrays are mutable in Scala.
Lists represents a linked list whereas arrays are flat.
Syntax:
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Some important points about list in Scala:
In a Scala list, each element must be of the same type.
The implementation of lists uses mutable state internally during construction.
In Scala, list is defined under scala.collection.immutable package.
A List has various methods to add, prepend, max, min, etc. to enhance the usage of list.
Example:
// Scala program to print immutable listsimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist1: List[String] = List("Geeks", "GFG", "GeeksforGeeks", "Geek123") val mylist2 = List("C", "C#", "Java", "Scala", "PHP", "Ruby") // Display the value of mylist1 println("List 1:") println(mylist1) // Display the value of mylist2 using for loop println("\nList 2:") for(mylist<-mylist2) { println(mylist) } }}
List 1:
List(Geeks, GFG, GeeksforGeeks, Geek123)
List 2:
C
C#
Java
Scala
PHP
Ruby
In above example simply we are printing two lists.Example:
// Scala program to illustrate the// use of empty listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println("The empty list is:") println(emptylist) }}
The empty list is:
List()
Above example shows that the list is empty or not.Example:
// Scala program to illustrate the // use of two dimensional listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a two-dimensional List. val twodlist: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) println("The two dimensional list is:") println(twodlist) }}
The two dimensional list is:
List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))
The following are the three basic operations which can be performed on list in scala:
head: The first element of a list returned by head method.Syntax:list.head //returns head of the list
Example:// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The head of the list is:") println(mylist.head) }} Output:The head of the list is:
C
tail: This method returns a list consisting of all elements except the first.Syntax:list.tail //returns a list consisting of all elements except the first
Example:// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The tail of the list is:") println(mylist.tail) }}Output:The tail of the list is:
List(C#, Java, Scala, PHP, Ruby)
isEmpty: This method returns true if the list is empty otherwise false.Syntax:list.isEmpty //returns true if the list is empty otherwise false.
Example:// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("List is empty or not:") println(mylist.isEmpty) }} Output:List is empty or not:
false
head: The first element of a list returned by head method.Syntax:list.head //returns head of the list
Example:// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The head of the list is:") println(mylist.head) }} Output:The head of the list is:
C
list.head //returns head of the list
Example:
// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The head of the list is:") println(mylist.head) }}
The head of the list is:
C
tail: This method returns a list consisting of all elements except the first.Syntax:list.tail //returns a list consisting of all elements except the first
Example:// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The tail of the list is:") println(mylist.tail) }}Output:The tail of the list is:
List(C#, Java, Scala, PHP, Ruby)
list.tail //returns a list consisting of all elements except the first
Example:
// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("The tail of the list is:") println(mylist.tail) }}
The tail of the list is:
List(C#, Java, Scala, PHP, Ruby)
isEmpty: This method returns true if the list is empty otherwise false.Syntax:list.isEmpty //returns true if the list is empty otherwise false.
Example:// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("List is empty or not:") println(mylist.isEmpty) }} Output:List is empty or not:
false
list.isEmpty //returns true if the list is empty otherwise false.
Example:
// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List("C", "C#", "Java", "Scala", "PHP", "Ruby") println("List is empty or not:") println(mylist.isEmpty) }}
List is empty or not:
false
Uniform List can be created in Scala using List.fill() method. List.fill() method creates a list and fills it with zero or more copies of an element.Syntax:
List.fill() //used to create uniform list in Scala
Example:
// Scala program to creating a uniform list import scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Repeats Scala three times. val programminglanguage = List.fill(3)("Scala") println( "Programming Language : " + programminglanguage ) // Repeats 2, 10 times. val number= List.fill(8)(4) println("number : " + number) }}
Programming Language : List(Scala, Scala, Scala)
number : List(4, 4, 4, 4, 4, 4, 4, 4)
The list order can be reversed in Scala using List.reverse method. List.reverse method can be used to reverse all elements of the list.Syntax:
list.reverse //used to reverse list in Scala
Example:
// Scala program of reversing a list orderimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mylist = List(1, 2, 3, 4, 5) println("Original list:" + mylist) // reversing a list println("Reverse list:" + mylist.reverse) }}
Original list:List(1, 2, 3, 4, 5)
Reverse list:List(5, 4, 3, 2, 1)
Picked
Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 253,
"s": 28,
"text": "A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items.Following are the point of difference between lists and array in Scala:"
},
{
"code": null,
"e": 310,
"s": 253,
"text": "Lists are immutable whereas arrays are mutable in Scala."
},
{
"code": null,
"e": 366,
"s": 310,
"text": "Lists represents a linked list whereas arrays are flat."
},
{
"code": null,
"e": 374,
"s": 366,
"text": "Syntax:"
},
{
"code": null,
"e": 482,
"s": 374,
"text": "val variable_name: List[type] = List(item1, item2, item3)\nor\nval variable_name = List(item1, item2, item3)\n"
},
{
"code": null,
"e": 525,
"s": 482,
"text": "Some important points about list in Scala:"
},
{
"code": null,
"e": 581,
"s": 525,
"text": "In a Scala list, each element must be of the same type."
},
{
"code": null,
"e": 660,
"s": 581,
"text": "The implementation of lists uses mutable state internally during construction."
},
{
"code": null,
"e": 728,
"s": 660,
"text": "In Scala, list is defined under scala.collection.immutable package."
},
{
"code": null,
"e": 817,
"s": 728,
"text": "A List has various methods to add, prepend, max, min, etc. to enhance the usage of list."
},
{
"code": null,
"e": 826,
"s": 817,
"text": "Example:"
},
{
"code": "// Scala program to print immutable listsimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist1: List[String] = List(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") val mylist2 = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") // Display the value of mylist1 println(\"List 1:\") println(mylist1) // Display the value of mylist2 using for loop println(\"\\nList 2:\") for(mylist<-mylist2) { println(mylist) } }}",
"e": 1516,
"s": 826,
"text": null
},
{
"code": null,
"e": 1600,
"s": 1516,
"text": "List 1:\nList(Geeks, GFG, GeeksforGeeks, Geek123)\n\nList 2:\nC\nC#\nJava\nScala\nPHP\nRuby\n"
},
{
"code": null,
"e": 1659,
"s": 1600,
"text": "In above example simply we are printing two lists.Example:"
},
{
"code": "// Scala program to illustrate the// use of empty listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println(\"The empty list is:\") println(emptylist) }}",
"e": 1985,
"s": 1659,
"text": null
},
{
"code": null,
"e": 2012,
"s": 1985,
"text": "The empty list is:\nList()\n"
},
{
"code": null,
"e": 2071,
"s": 2012,
"text": "Above example shows that the list is empty or not.Example:"
},
{
"code": "// Scala program to illustrate the // use of two dimensional listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a two-dimensional List. val twodlist: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) println(\"The two dimensional list is:\") println(twodlist) }}",
"e": 2521,
"s": 2071,
"text": null
},
{
"code": null,
"e": 2601,
"s": 2521,
"text": "The two dimensional list is:\nList(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))\n"
},
{
"code": null,
"e": 2687,
"s": 2601,
"text": "The following are the three basic operations which can be performed on list in scala:"
},
{
"code": null,
"e": 4417,
"s": 2687,
"text": "head: The first element of a list returned by head method.Syntax:list.head //returns head of the list\nExample:// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The head of the list is:\") println(mylist.head) }} Output:The head of the list is:\nC\ntail: This method returns a list consisting of all elements except the first.Syntax:list.tail //returns a list consisting of all elements except the first\nExample:// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The tail of the list is:\") println(mylist.tail) }}Output:The tail of the list is:\nList(C#, Java, Scala, PHP, Ruby)\nisEmpty: This method returns true if the list is empty otherwise false.Syntax:list.isEmpty //returns true if the list is empty otherwise false.\nExample:// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"List is empty or not:\") println(mylist.isEmpty) }} Output:List is empty or not:\nfalse\n"
},
{
"code": null,
"e": 4954,
"s": 4417,
"text": "head: The first element of a list returned by head method.Syntax:list.head //returns head of the list\nExample:// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The head of the list is:\") println(mylist.head) }} Output:The head of the list is:\nC\n"
},
{
"code": null,
"e": 4992,
"s": 4954,
"text": "list.head //returns head of the list\n"
},
{
"code": null,
"e": 5001,
"s": 4992,
"text": "Example:"
},
{
"code": "// Scala program of a list to // perform head operationimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The head of the list is:\") println(mylist.head) }} ",
"e": 5394,
"s": 5001,
"text": null
},
{
"code": null,
"e": 5422,
"s": 5394,
"text": "The head of the list is:\nC\n"
},
{
"code": null,
"e": 6033,
"s": 5422,
"text": "tail: This method returns a list consisting of all elements except the first.Syntax:list.tail //returns a list consisting of all elements except the first\nExample:// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The tail of the list is:\") println(mylist.tail) }}Output:The tail of the list is:\nList(C#, Java, Scala, PHP, Ruby)\n"
},
{
"code": null,
"e": 6105,
"s": 6033,
"text": "list.tail //returns a list consisting of all elements except the first\n"
},
{
"code": null,
"e": 6114,
"s": 6105,
"text": "Example:"
},
{
"code": "// Scala program to perform// tail operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"The tail of the list is:\") println(mylist.tail) }}",
"e": 6497,
"s": 6114,
"text": null
},
{
"code": null,
"e": 6556,
"s": 6497,
"text": "The tail of the list is:\nList(C#, Java, Scala, PHP, Ruby)\n"
},
{
"code": null,
"e": 7140,
"s": 6556,
"text": "isEmpty: This method returns true if the list is empty otherwise false.Syntax:list.isEmpty //returns true if the list is empty otherwise false.\nExample:// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"List is empty or not:\") println(mylist.isEmpty) }} Output:List is empty or not:\nfalse\n"
},
{
"code": null,
"e": 7207,
"s": 7140,
"text": "list.isEmpty //returns true if the list is empty otherwise false.\n"
},
{
"code": null,
"e": 7216,
"s": 7207,
"text": "Example:"
},
{
"code": "// Scala program to perform// isEmpty operation of a listimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val mylist = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") println(\"List is empty or not:\") println(mylist.isEmpty) }} ",
"e": 7613,
"s": 7216,
"text": null
},
{
"code": null,
"e": 7642,
"s": 7613,
"text": "List is empty or not:\nfalse\n"
},
{
"code": null,
"e": 7799,
"s": 7642,
"text": "Uniform List can be created in Scala using List.fill() method. List.fill() method creates a list and fills it with zero or more copies of an element.Syntax:"
},
{
"code": null,
"e": 7852,
"s": 7799,
"text": "List.fill() //used to create uniform list in Scala \n"
},
{
"code": null,
"e": 7861,
"s": 7852,
"text": "Example:"
},
{
"code": "// Scala program to creating a uniform list import scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Repeats Scala three times. val programminglanguage = List.fill(3)(\"Scala\") println( \"Programming Language : \" + programminglanguage ) // Repeats 2, 10 times. val number= List.fill(8)(4) println(\"number : \" + number) }} ",
"e": 8310,
"s": 7861,
"text": null
},
{
"code": null,
"e": 8398,
"s": 8310,
"text": "Programming Language : List(Scala, Scala, Scala)\nnumber : List(4, 4, 4, 4, 4, 4, 4, 4)\n"
},
{
"code": null,
"e": 8541,
"s": 8398,
"text": "The list order can be reversed in Scala using List.reverse method. List.reverse method can be used to reverse all elements of the list.Syntax:"
},
{
"code": null,
"e": 8588,
"s": 8541,
"text": "list.reverse //used to reverse list in Scala \n"
},
{
"code": null,
"e": 8597,
"s": 8588,
"text": "Example:"
},
{
"code": "// Scala program of reversing a list orderimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mylist = List(1, 2, 3, 4, 5) println(\"Original list:\" + mylist) // reversing a list println(\"Reverse list:\" + mylist.reverse) }} ",
"e": 8938,
"s": 8597,
"text": null
},
{
"code": null,
"e": 9006,
"s": 8938,
"text": "Original list:List(1, 2, 3, 4, 5)\nReverse list:List(5, 4, 3, 2, 1)\n"
},
{
"code": null,
"e": 9013,
"s": 9006,
"text": "Picked"
},
{
"code": null,
"e": 9019,
"s": 9013,
"text": "Scala"
},
{
"code": null,
"e": 9025,
"s": 9019,
"text": "Scala"
}
]
|
Starting off in Bioinformatics — Turning DNA sequences into Protein sequences | by Vijini Mallawaarachchi | Towards Data Science | In this article, we will be learning about proteins and how to convert a DNA sequence into a protein sequence. I suggest you read my previous article on DNA nuleotides and strands if you missed it, so this article will make more sense as you read. So let’s move on to proteins.
Proteins are large chainlike molecules which are made out of amino acids. Proteins differ from one another mainly in their sequence of amino acids, which is decided by the nucleotide sequence of their genes. Before moving on to proteins, let’s see what amino acids are.
Amino acids are complex organic molecules, primarily made of carbon, hydrogen, oxygen, and nitrogen, along with a few other atoms. It contains an amine group and a carboxyl group, along with a side chain (R group) which is specific to each amino acid.
About 500 amino acids are known at present but only 20 appear in our genetic code. These 20 amino acids are the building blocks in which we are interested in.
The diagram given below shows the 20 common amino acids which appear in our genetic code, along with their full names, three-letter codes, and one-letter codes.
Biochemists have recognized that a given type of protein always contains precisely the same number of total amino acids (generically called residues) in the same proportion. For example,
insulin = (30 glycines + 44 alanines + 5 tyrosines + 14 glutamines + . . .)
Furthermore, amino acids are linked together as a chain. The identity of a protein is obtained from its composition as well as the precise order of its constituent amino acids. Hence insulin can be represented as,
insulin = MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERG FFYTPKTRREAEDLQVGQVELGGGPGAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN
Proteins are formed by amino acids with their amine and carboxyl groups to form the bonds known as peptide bonds between the successive residues in the sequence. The two diagrams given below depicts how free amino acids form a protein by forming peptide bonds.
You can see that there is an unused amine group on the left extreme and an unused carboxyl group on the right extreme. These extremities are respectively called the N-terminus and C-terminus of the protein chain. The sequence of a protein is read by its constituent amino acids, listed in order from the N-terminus to the C-terminus. Hence the sequence of the protein found in the above diagram will be,
MAVLD = Met-Ala-Val-Leu-Asp = Methionine–Alanine-Valine–Leucine-Aspartic
When you know a DNA sequence, you can translate it into the corresponding protein sequence by using the genetic code. This is the same way the cell itself generates a protein sequence. This process is known as DNA to protein translation.
The genetic code (referred as DNA codon table for DNA sequences) shows how we uniquely relate a 4-nucleotide sequence (A, T, G, C) to a set of 20 amino acids. It describes a set of rules by which information encoded within genetic material is translated into proteins by living cells. The diagram given below shows the DNA codon table in the form of a chart.
First you should get your DNA string.
ATGGAAGTATTTAAAGCGCCACCTATTGGGATATAAG
Then start reading sequences of 3 nucleotides (one triplet) at a time.
ATG GAA GTA TTT AAA GCG CCA CCT ATT GGG ATA TAA G...
Now, use the genetic code chart to read which amino acid corresponds to the current triplet (technically referred to as codons). The first circle starting from the center represents the first character of the triplet, the second circle represents the second character and the third circle represents the last character. After translating, you will get the protein sequence which corresponds to the aforementioned DNA sequence.
M E V F K A P P I G I STOPM E V F K A P P I G I
TAA, TAG and TGA are known as termination signals where you stop the translation process.
The Python code given below takes a DNA sequence and converts it to the corresponding protein sequence. I have created a dictionary to store the information of the genetic code chart. Feel free to try out the code and see what happens.
I have given the same DNA sequence we discussed previously as input in the sample_dna.txt file.
ATGGAAGTATTTAAAGCGCCACCTATTGGGATATAAG
Given below are the results obtained.
If you know where a protein-coding region starts in a DNA sequence, your computer can generate the corresponding protein sequence consisting of the amino acids, using a simple code. Many sequence analysis programs use this translation method, so you can process DNA sequences as virtual protein sequences using your computer.
Hope you enjoyed reading this article and learned something useful.
Since I’m still very new to this field, I would like to hear your advice. 😇
Stay tuned for my next article on bioinformatics which will be about RNA sequences.
Thanks for reading... 😃 | [
{
"code": null,
"e": 450,
"s": 172,
"text": "In this article, we will be learning about proteins and how to convert a DNA sequence into a protein sequence. I suggest you read my previous article on DNA nuleotides and strands if you missed it, so this article will make more sense as you read. So let’s move on to proteins."
},
{
"code": null,
"e": 720,
"s": 450,
"text": "Proteins are large chainlike molecules which are made out of amino acids. Proteins differ from one another mainly in their sequence of amino acids, which is decided by the nucleotide sequence of their genes. Before moving on to proteins, let’s see what amino acids are."
},
{
"code": null,
"e": 972,
"s": 720,
"text": "Amino acids are complex organic molecules, primarily made of carbon, hydrogen, oxygen, and nitrogen, along with a few other atoms. It contains an amine group and a carboxyl group, along with a side chain (R group) which is specific to each amino acid."
},
{
"code": null,
"e": 1131,
"s": 972,
"text": "About 500 amino acids are known at present but only 20 appear in our genetic code. These 20 amino acids are the building blocks in which we are interested in."
},
{
"code": null,
"e": 1292,
"s": 1131,
"text": "The diagram given below shows the 20 common amino acids which appear in our genetic code, along with their full names, three-letter codes, and one-letter codes."
},
{
"code": null,
"e": 1479,
"s": 1292,
"text": "Biochemists have recognized that a given type of protein always contains precisely the same number of total amino acids (generically called residues) in the same proportion. For example,"
},
{
"code": null,
"e": 1555,
"s": 1479,
"text": "insulin = (30 glycines + 44 alanines + 5 tyrosines + 14 glutamines + . . .)"
},
{
"code": null,
"e": 1769,
"s": 1555,
"text": "Furthermore, amino acids are linked together as a chain. The identity of a protein is obtained from its composition as well as the precise order of its constituent amino acids. Hence insulin can be represented as,"
},
{
"code": null,
"e": 1891,
"s": 1769,
"text": "insulin = MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERG FFYTPKTRREAEDLQVGQVELGGGPGAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN"
},
{
"code": null,
"e": 2152,
"s": 1891,
"text": "Proteins are formed by amino acids with their amine and carboxyl groups to form the bonds known as peptide bonds between the successive residues in the sequence. The two diagrams given below depicts how free amino acids form a protein by forming peptide bonds."
},
{
"code": null,
"e": 2556,
"s": 2152,
"text": "You can see that there is an unused amine group on the left extreme and an unused carboxyl group on the right extreme. These extremities are respectively called the N-terminus and C-terminus of the protein chain. The sequence of a protein is read by its constituent amino acids, listed in order from the N-terminus to the C-terminus. Hence the sequence of the protein found in the above diagram will be,"
},
{
"code": null,
"e": 2634,
"s": 2556,
"text": "MAVLD = Met-Ala-Val-Leu-Asp = Methionine–Alanine-Valine–Leucine-Aspartic"
},
{
"code": null,
"e": 2872,
"s": 2634,
"text": "When you know a DNA sequence, you can translate it into the corresponding protein sequence by using the genetic code. This is the same way the cell itself generates a protein sequence. This process is known as DNA to protein translation."
},
{
"code": null,
"e": 3231,
"s": 2872,
"text": "The genetic code (referred as DNA codon table for DNA sequences) shows how we uniquely relate a 4-nucleotide sequence (A, T, G, C) to a set of 20 amino acids. It describes a set of rules by which information encoded within genetic material is translated into proteins by living cells. The diagram given below shows the DNA codon table in the form of a chart."
},
{
"code": null,
"e": 3269,
"s": 3231,
"text": "First you should get your DNA string."
},
{
"code": null,
"e": 3307,
"s": 3269,
"text": "ATGGAAGTATTTAAAGCGCCACCTATTGGGATATAAG"
},
{
"code": null,
"e": 3378,
"s": 3307,
"text": "Then start reading sequences of 3 nucleotides (one triplet) at a time."
},
{
"code": null,
"e": 3431,
"s": 3378,
"text": "ATG GAA GTA TTT AAA GCG CCA CCT ATT GGG ATA TAA G..."
},
{
"code": null,
"e": 3858,
"s": 3431,
"text": "Now, use the genetic code chart to read which amino acid corresponds to the current triplet (technically referred to as codons). The first circle starting from the center represents the first character of the triplet, the second circle represents the second character and the third circle represents the last character. After translating, you will get the protein sequence which corresponds to the aforementioned DNA sequence."
},
{
"code": null,
"e": 3906,
"s": 3858,
"text": "M E V F K A P P I G I STOPM E V F K A P P I G I"
},
{
"code": null,
"e": 3996,
"s": 3906,
"text": "TAA, TAG and TGA are known as termination signals where you stop the translation process."
},
{
"code": null,
"e": 4232,
"s": 3996,
"text": "The Python code given below takes a DNA sequence and converts it to the corresponding protein sequence. I have created a dictionary to store the information of the genetic code chart. Feel free to try out the code and see what happens."
},
{
"code": null,
"e": 4328,
"s": 4232,
"text": "I have given the same DNA sequence we discussed previously as input in the sample_dna.txt file."
},
{
"code": null,
"e": 4366,
"s": 4328,
"text": "ATGGAAGTATTTAAAGCGCCACCTATTGGGATATAAG"
},
{
"code": null,
"e": 4404,
"s": 4366,
"text": "Given below are the results obtained."
},
{
"code": null,
"e": 4730,
"s": 4404,
"text": "If you know where a protein-coding region starts in a DNA sequence, your computer can generate the corresponding protein sequence consisting of the amino acids, using a simple code. Many sequence analysis programs use this translation method, so you can process DNA sequences as virtual protein sequences using your computer."
},
{
"code": null,
"e": 4798,
"s": 4730,
"text": "Hope you enjoyed reading this article and learned something useful."
},
{
"code": null,
"e": 4874,
"s": 4798,
"text": "Since I’m still very new to this field, I would like to hear your advice. 😇"
},
{
"code": null,
"e": 4958,
"s": 4874,
"text": "Stay tuned for my next article on bioinformatics which will be about RNA sequences."
}
]
|
How to add a new column to represent the percentage for groups in an R data frame? | In data analysis, we often need to find the percentage of values that exists in a data group. This helps us to understand which value occurs frequently and which one has low frequency. Also, plotting of percentages through pie charts can be done and that gives a better view of the data to the readers. Adding a new column as percentage for groups is not a challenge if we can use mutate function of dplyr package, here you will get the examples from that.
Live Demo
> Group<-rep(1:2,each=5)
> Frequency<-sample(1:100,10)
> df1<-data.frame(Group,Frequency)
> df1
Group Frequency
1 1 67
2 1 58
3 1 54
4 1 13
5 1 23
6 2 91
7 2 3
8 2 95
9 2 38
10 2 48
> library(dplyr)
Finding the percentage for each group values in the group −
> df1%>%group_by(Group)%>%mutate(Percentage=paste0(round(Frequency/sum(Frequency)*100,2),"%"))
# A tibble: 10 x 3
# Groups: Group [2]
Group Frequency Percentage
<int> <int> <chr>
1 1 67 31.16%
2 1 58 26.98%
3 1 54 25.12%
4 1 13 6.05%
5 1 23 10.7%
6 2 91 33.09%
7 2 3 1.09%
8 2 95 34.55%
9 2 38 13.82%
10 2 48 17.45%
Live Demo
> Gender<-rep(c("Male","Female"),each=5)
> Salary<-sample(25000:50000,10)
> df2<-data.frame(Gender,Salary)
> df2
Gender Salary
1 Male 41734
2 Male 39035
3 Male 36161
4 Male 33437
5 Male 45123
6 Female 44492
7 Female 48456
8 Female 31569
9 Female 35110
10 Female 43630
>df2%>%group_by(Gender)%>%mutate(Percentage=paste0(round(Salary/sum(Salary)*1
00,2),"%"))
# A tibble: 10 x 3
# Groups: Gender [2]
Gender Salary Percentage
<fct> <int> <chr>
1 Male 41734 21.35%
2 Male 39035 19.97%
3 Male 36161 18.5%
4 Male 33437 17.1%
5 Male 45123 23.08%
6 Female 44492 21.89%
7 Female 48456 23.84%
8 Female 31569 15.53%
9 Female 35110 17.27%
10 Female 43630 21.47%
Live Demo
> Grade<-rep(c("A","B","C","D","E"),each=2)
> Number_of_Years_in_Job<-sample(1:5,10,replace=TRUE)
> df3<-data.frame(Grade,Number_of_Years_in_Job)
> df3
Grade Number_of_Years_in_Job
1 A 4
2 A 5
3 B 4
4 B 4
5 C 1
6 C 4
7 D 1
8 D 1
9 E 3
10 E 1
>df3%>%group_by(Grade)%>%mutate(Percentage=paste0(round(Number_of_Years_in_J
ob/sum(Number_of_Years_in_Job)*100,2),"%"))
# A tibble: 10 x 3
# Groups: Grade [5]
Grade Number_of_Years_in_Job Percentage
<fct> <int> <chr>
1 A 4 44.44%
2 A 5 55.56%
3 B 4 50%
4 B 4 50%
5 C 1 20%
6 C 4 80%
7 D 1 50%
8 D 1 50%
9 E 3 75%
10 E 1 25% | [
{
"code": null,
"e": 1519,
"s": 1062,
"text": "In data analysis, we often need to find the percentage of values that exists in a data group. This helps us to understand which value occurs frequently and which one has low frequency. Also, plotting of percentages through pie charts can be done and that gives a better view of the data to the readers. Adding a new column as percentage for groups is not a challenge if we can use mutate function of dplyr package, here you will get the examples from that."
},
{
"code": null,
"e": 1530,
"s": 1519,
"text": " Live Demo"
},
{
"code": null,
"e": 1626,
"s": 1530,
"text": "> Group<-rep(1:2,each=5)\n> Frequency<-sample(1:100,10)\n> df1<-data.frame(Group,Frequency)\n> df1"
},
{
"code": null,
"e": 1712,
"s": 1626,
"text": "Group Frequency\n1 1 67\n2 1 58\n3 1 54\n4 1 13\n5 1 23\n6 2 91\n7 2 3\n8 2 95\n9 2 38\n10 2 48"
},
{
"code": null,
"e": 1729,
"s": 1712,
"text": "> library(dplyr)"
},
{
"code": null,
"e": 1789,
"s": 1729,
"text": "Finding the percentage for each group values in the group −"
},
{
"code": null,
"e": 1923,
"s": 1789,
"text": "> df1%>%group_by(Group)%>%mutate(Percentage=paste0(round(Frequency/sum(Frequency)*100,2),\"%\"))\n# A tibble: 10 x 3\n# Groups: Group [2]"
},
{
"code": null,
"e": 2166,
"s": 1923,
"text": "Group Frequency Percentage\n <int> <int> <chr>\n1 1 67 31.16%\n2 1 58 26.98%\n3 1 54 25.12%\n4 1 13 6.05%\n5 1 23 10.7%\n6 2 91 33.09%\n7 2 3 1.09%\n8 2 95 34.55%\n9 2 38 13.82%\n10 2 48 17.45%"
},
{
"code": null,
"e": 2177,
"s": 2166,
"text": " Live Demo"
},
{
"code": null,
"e": 2290,
"s": 2177,
"text": "> Gender<-rep(c(\"Male\",\"Female\"),each=5)\n> Salary<-sample(25000:50000,10)\n> df2<-data.frame(Gender,Salary)\n> df2"
},
{
"code": null,
"e": 2466,
"s": 2290,
"text": " Gender Salary\n1 Male 41734\n2 Male 39035\n3 Male 36161\n4 Male 33437\n5 Male 45123\n6 Female 44492\n7 Female 48456\n8 Female 31569\n9 Female 35110\n10 Female 43630"
},
{
"code": null,
"e": 2596,
"s": 2466,
"text": ">df2%>%group_by(Gender)%>%mutate(Percentage=paste0(round(Salary/sum(Salary)*1\n00,2),\"%\"))\n# A tibble: 10 x 3\n# Groups: Gender [2]"
},
{
"code": null,
"e": 2903,
"s": 2596,
"text": " Gender Salary Percentage\n <fct> <int> <chr>\n1 Male 41734 21.35%\n2 Male 39035 19.97%\n3 Male 36161 18.5%\n4 Male 33437 17.1%\n5 Male 45123 23.08%\n6 Female 44492 21.89%\n7 Female 48456 23.84%\n8 Female 31569 15.53%\n9 Female 35110 17.27%\n10 Female 43630 21.47%"
},
{
"code": null,
"e": 2914,
"s": 2903,
"text": " Live Demo"
},
{
"code": null,
"e": 3066,
"s": 2914,
"text": "> Grade<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),each=2)\n> Number_of_Years_in_Job<-sample(1:5,10,replace=TRUE)\n> df3<-data.frame(Grade,Number_of_Years_in_Job)\n> df3"
},
{
"code": null,
"e": 3248,
"s": 3066,
"text": " Grade Number_of_Years_in_Job\n1 A 4\n2 A 5\n3 B 4\n4 B 4\n5 C 1\n6 C 4\n7 D 1\n8 D 1\n9 E 3\n10 E 1"
},
{
"code": null,
"e": 3408,
"s": 3248,
"text": ">df3%>%group_by(Grade)%>%mutate(Percentage=paste0(round(Number_of_Years_in_J\nob/sum(Number_of_Years_in_Job)*100,2),\"%\"))\n# A tibble: 10 x 3\n# Groups: Grade [5]"
},
{
"code": null,
"e": 3634,
"s": 3408,
"text": "Grade Number_of_Years_in_Job Percentage\n <fct> <int> <chr>\n1 A 4 44.44%\n2 A 5 55.56%\n3 B 4 50%\n4 B 4 50%\n5 C 1 20%\n6 C 4 80%\n7 D 1 50%\n8 D 1 50%\n9 E 3 75%\n10 E 1 25%"
}
]
|
Longest Uncommon Subsequence | 09 Jun, 2021
Given two strings, find the length of longest uncommon subsequence of the two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings which is not a subsequence of other strings. Examples:
Input : "abcd", "abc"
Output : 4
The longest subsequence is 4 because "abcd"
is a subsequence of first string, but not
a subsequence of second string.
Input : "abc", "abc"
Output : 0
Both strings are same, so there is no
uncommon subsequence.
Brute Force: In general, the first thought some people may have is to generate all possible 2n subsequences of both the strings and store their frequency in a hashmap. Longest subsequence whose frequency is equal to 1 will be the required subsequence.
C++
Java
Python3
C#
Javascript
// CPP program to find longest uncommon// subsequence using naive method#include <iostream>#include <unordered_map>#include <vector>using namespace std; // function to calculate length of longest uncommon subsequenceint findLUSlength(string a, string b){ /* creating an unordered map to map strings to their frequency*/ unordered_map<string, int> map; vector<string> strArr; strArr.push_back(a); strArr.push_back(b); // traversing all elements of vector strArr for (string s : strArr) { /* Creating all possible subsequences, i.e 2^n*/ for (int i = 0; i < (1 << s.length()); i++) { string t = ""; for (int j = 0; j < s.length(); j++) { /* ((i>>j) & 1) determines which character goes into string t*/ if (((i >> j) & 1) != 0) t += s[j]; } /* If common subsequence is found, increment its frequency*/ if (map.count(t)) map[t]++; else map[t] = 1; } } int res = 0; for (auto a : map) // traversing the map { // if frequency equals 1 if (a.second == 1) res = max(res, (int)a.first.length()); } return res;}int main(){ // Your C++ Code string a = "abcdabcd", b = "abcabc"; // input strings cout << findLUSlength(a, b); return 0;}
// Java program to find longest uncommon// subsequence using naive methodimport java.io.*;import java.util.*; class GfG{ // function to calculate length of// longest uncommon subsequencestatic int findLUSlength(String a, String b){ // creating an unordered map to map // strings to their frequency HashMap<String, Integer> map= new HashMap<String, Integer>(); Vector<String> strArr= new Vector<String>(); strArr.add(a); strArr.add(b); // traversing all elements of vector strArr for (String s : strArr) { // Creating all possible subsequences, i.e 2^n for (int i = 0; i < (1 << s.length()); i++) { String t = ""; for (int j = 0; j < s.length(); j++) { // ((i>>j) & 1) determines which // character goes into string t if (((i >> j) & 1) != 0) t += s.charAt(j); } // If common subsequence is found, // increment its frequency if (map.containsKey(t)) map.put(t,map.get(t)+1); else map.put(t,1); } } int res = 0; for (HashMap.Entry<String, Integer> entry : map.entrySet()) // traversing the map { // if frequency equals 1 if (entry.getValue() == 1) res = Math.max(res, entry.getKey().length()); } return res;} // Driver code public static void main (String[] args) { // input strings String a = "abcdabcd", b = "abcabc"; System.out.println(findLUSlength(a, b)); }} // This code is contributed by Gitanjali.
# Python3 program to find longest uncommon# subsequence using naive method # function to calculate length of# longest uncommon subsequencedef findLUSlength(a, b): ''' creating an unordered map to map strings to their frequency''' map = dict() strArr = [] strArr.append(a) strArr.append(b) # traversing all elements of vector strArr for s in strArr: ''' Creating all possible subsequences, i.e 2^n''' for i in range(1 << len(s)): t = "" for j in range(len(s)): ''' ((i>>j) & 1) determines which character goes into t''' if (((i >> j) & 1) != 0): t += s[j] # If common subsequence is found, # increment its frequency if (t in map.keys()): map[t] += 1; else: map[t] = 1 res = 0 for a in map: # traversing the map # if frequency equals 1 if (map[a] == 1): res = max(res, len(a)) return res # Driver Codea = "abcdabcd"b = "abcabc" # input stringsprint(findLUSlength(a, b)) # This code is contributed by Mohit Kumar
// C# program to find longest// uncommon subsequence using// naive methodusing System;using System.Collections.Generic; class GFG{ // function to calculate // length of longest // uncommon subsequence static int findLUSlength(string a, string b) { // creating an unordered // map to map strings to // their frequency Dictionary<string, int> map = new Dictionary<string, int>(); List<string> strArr = new List<string>(); strArr.Add(a); strArr.Add(b); // traversing all elements // of vector strArr foreach (string s in strArr) { // Creating all possible // subsequences, i.e 2^n for (int i = 0; i < (1 << s.Length); i++) { string t = ""; for (int j = 0; j < s.Length; j++) { // ((i>>j) & 1) determines // which character goes // into string t if (((i >> j) & 1) != 0) t += s[j]; } // If common subsequence // is found, increment // its frequency if (map.ContainsKey(t)) { int value = map[t] + 1; map.Remove(t); map.Add(t, value); } else map.Add(t, 1); } } int res = 0; foreach (KeyValuePair<string, int> entry in map) // traversing the map { // if frequency equals 1 if (entry.Value == 1) res = Math.Max(res, entry.Key.Length); } return res; } // Driver code static void Main () { // input strings string a = "abcdabcd", b = "abcabc"; Console.Write(findLUSlength(a, b)); }} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // JavaScript program to find longest uncommon// subsequence using naive method // function to calculate length of// longest uncommon subsequence function findLUSlength(a,b) { // creating an unordered map to map // strings to their frequency let map= new Map(); let strArr= []; strArr.push(a); strArr.push(b); // traversing all elements of vector strArr for (let s=0; s<strArr.length;s++) { // Creating all possible subsequences, i.e 2^n for (let i = 0; i < (1 << strArr[s].length); i++) { let t = ""; for (let j = 0; j < strArr[s].length; j++) { // ((i>>j) & 1) determines which // character goes into string t if (((i >> j) & 1) != 0) t += strArr[s][j]; } // If common subsequence is found, // increment its frequency if (map.has(t)) map.set(t,map.get(t)+1); else map.set(t,1); } } let res = 0; for (let [key, value] of map.entries()) // traversing the map { // if frequency equals 1 if (value == 1) res = Math.max(res, key.length); } return res; } // Driver code // input strings let a = "abcdabcd", b = "abcabc"; document.write(findLUSlength(a, b)); // This code is contributed by unknown2108 </script>
Output:
8
Time complexity: O(2x + 2y), where x and y are the lengths of two strings.
Auxiliary Space : O(2x + 2y).
Efficient Algorithm: If we analyze the problem carefully, it would seem much easier than it looks. All the three possible cases are as described below;
If both the strings are identical, for example: “ac” and “ac”, it is obvious that no subsequence will be uncommon. Hence, return 0.If length(a) = length(b) and a ? b, for example: “abcdef” and “defghi”, out of these two strings one string will never be a subsequence of other string. Hence, return length(a) or length(b).If length(a) ? length(b), for example: “abcdabcd” and “abcabc”, in this case we can consider bigger string as a required subsequence because bigger string can not be a subsequence of smaller string. Hence, return max(length(a), length(b)).
If both the strings are identical, for example: “ac” and “ac”, it is obvious that no subsequence will be uncommon. Hence, return 0.
If length(a) = length(b) and a ? b, for example: “abcdef” and “defghi”, out of these two strings one string will never be a subsequence of other string. Hence, return length(a) or length(b).
If length(a) ? length(b), for example: “abcdabcd” and “abcabc”, in this case we can consider bigger string as a required subsequence because bigger string can not be a subsequence of smaller string. Hence, return max(length(a), length(b)).
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find longest uncommon// subsequence.#include <iostream>using namespace std; // function to calculate length of longest// uncommon subsequenceint findLUSlength(string a, string b){ // Case 1: If strings are equal if (!a.compare(b)) return 0; // for case 2 and case 3 return max(a.length(), b.length());} // Driver codeint main(){ string a = "abcdabcd", b = "abcabc"; cout << findLUSlength(a, b); return 0;}
// Java program to find longest uncommon// subsequence using naive method import java.io.*;import java.util.*; class GfG{ // function to calculate length of longest// uncommon subsequencestatic int findLUSlength(String a, String b){ // Case 1: If strings are equal if (a.equals(b)==true) return 0; // for case 2 and case 3 return Math.max(a.length(), b.length());} // Driver code public static void main (String[] args) { // input strings String a = "abcdabcd", b = "abcabc"; System.out.println(findLUSlength(a, b)); }} // This code is contributed by Gitanjali.
# Python program to find# longest uncommon# subsequence using naive method import math # function to calculate# length of longest# uncommon subsequencedef findLUSlength( a, b): # Case 1: If strings are equal if (a==b) : return 0 # for case 2 and case 3 return max(len(a), len(b)) # Driver code #input stringsa = "abcdabcd"b = "abcabc"print (findLUSlength(a, b)) # This code is contributed by Gitanjali.
// C# program to find longest uncommon// subsequence using naive method.using System; class GfG { // function to calculate length // of longest uncommon subsequence static int findLUSlength(String a, String b) { // Case 1: If strings are equal if (a.Equals(b)==true) return 0; // for case 2 and case 3 return Math.Max(a.Length, b.Length); } // Driver code public static void Main () { // input strings String a = "abcdabcd", b = "abcabc"; Console.Write(findLUSlength(a, b)); }} // This code is contributed by nitin mittal.
<?php// PHP Program to find longest// uncommon subsequence. // function to calculate length// of longest uncommon subsequencefunction findLUSlength($a, $b){ // Case 1: If strings // are equal if (!strcmp($a, $b)) return 0; // for case 2 // and case 3 return max(strlen($a), strlen($b));} // Driver code$a = "abcdabcd";$b = "abcabc";echo (findLUSlength($a, $b)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // JavaScript Program to find longest uncommon// subsequence. // function to calculate length of longest// uncommon subsequencefunction findLUSlength(a, b){ // Case 1: If strings are equal if (a===b) return 0; // for case 2 and case 3 return Math.max(a.length, b.length);} // Driver codevar a = "abcdabcd", b = "abcabc";document.write( findLUSlength(a, b)); </script>
Output:
8
Complexity Analysis:
Time complexity: O(min(x, y)), where x and y are the lengths of two strings.
Auxiliary Space: O(1).
nitin mittal
manishshaw1
mohit kumar 29
unknown2108
noob2000
subsequence
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Remove first and last character of a string in Java
Check if an URL is valid or not using Regular Expression
Find the smallest window in a string containing all characters of another string | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 291,
"s": 52,
"text": "Given two strings, find the length of longest uncommon subsequence of the two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings which is not a subsequence of other strings. Examples: "
},
{
"code": null,
"e": 536,
"s": 291,
"text": "Input : \"abcd\", \"abc\"\nOutput : 4\nThe longest subsequence is 4 because \"abcd\"\nis a subsequence of first string, but not\na subsequence of second string.\n\nInput : \"abc\", \"abc\"\nOutput : 0\nBoth strings are same, so there is no \nuncommon subsequence."
},
{
"code": null,
"e": 792,
"s": 538,
"text": "Brute Force: In general, the first thought some people may have is to generate all possible 2n subsequences of both the strings and store their frequency in a hashmap. Longest subsequence whose frequency is equal to 1 will be the required subsequence. "
},
{
"code": null,
"e": 796,
"s": 792,
"text": "C++"
},
{
"code": null,
"e": 801,
"s": 796,
"text": "Java"
},
{
"code": null,
"e": 809,
"s": 801,
"text": "Python3"
},
{
"code": null,
"e": 812,
"s": 809,
"text": "C#"
},
{
"code": null,
"e": 823,
"s": 812,
"text": "Javascript"
},
{
"code": "// CPP program to find longest uncommon// subsequence using naive method#include <iostream>#include <unordered_map>#include <vector>using namespace std; // function to calculate length of longest uncommon subsequenceint findLUSlength(string a, string b){ /* creating an unordered map to map strings to their frequency*/ unordered_map<string, int> map; vector<string> strArr; strArr.push_back(a); strArr.push_back(b); // traversing all elements of vector strArr for (string s : strArr) { /* Creating all possible subsequences, i.e 2^n*/ for (int i = 0; i < (1 << s.length()); i++) { string t = \"\"; for (int j = 0; j < s.length(); j++) { /* ((i>>j) & 1) determines which character goes into string t*/ if (((i >> j) & 1) != 0) t += s[j]; } /* If common subsequence is found, increment its frequency*/ if (map.count(t)) map[t]++; else map[t] = 1; } } int res = 0; for (auto a : map) // traversing the map { // if frequency equals 1 if (a.second == 1) res = max(res, (int)a.first.length()); } return res;}int main(){ // Your C++ Code string a = \"abcdabcd\", b = \"abcabc\"; // input strings cout << findLUSlength(a, b); return 0;}",
"e": 2245,
"s": 823,
"text": null
},
{
"code": "// Java program to find longest uncommon// subsequence using naive methodimport java.io.*;import java.util.*; class GfG{ // function to calculate length of// longest uncommon subsequencestatic int findLUSlength(String a, String b){ // creating an unordered map to map // strings to their frequency HashMap<String, Integer> map= new HashMap<String, Integer>(); Vector<String> strArr= new Vector<String>(); strArr.add(a); strArr.add(b); // traversing all elements of vector strArr for (String s : strArr) { // Creating all possible subsequences, i.e 2^n for (int i = 0; i < (1 << s.length()); i++) { String t = \"\"; for (int j = 0; j < s.length(); j++) { // ((i>>j) & 1) determines which // character goes into string t if (((i >> j) & 1) != 0) t += s.charAt(j); } // If common subsequence is found, // increment its frequency if (map.containsKey(t)) map.put(t,map.get(t)+1); else map.put(t,1); } } int res = 0; for (HashMap.Entry<String, Integer> entry : map.entrySet()) // traversing the map { // if frequency equals 1 if (entry.getValue() == 1) res = Math.max(res, entry.getKey().length()); } return res;} // Driver code public static void main (String[] args) { // input strings String a = \"abcdabcd\", b = \"abcabc\"; System.out.println(findLUSlength(a, b)); }} // This code is contributed by Gitanjali.",
"e": 3853,
"s": 2245,
"text": null
},
{
"code": "# Python3 program to find longest uncommon# subsequence using naive method # function to calculate length of# longest uncommon subsequencedef findLUSlength(a, b): ''' creating an unordered map to map strings to their frequency''' map = dict() strArr = [] strArr.append(a) strArr.append(b) # traversing all elements of vector strArr for s in strArr: ''' Creating all possible subsequences, i.e 2^n''' for i in range(1 << len(s)): t = \"\" for j in range(len(s)): ''' ((i>>j) & 1) determines which character goes into t''' if (((i >> j) & 1) != 0): t += s[j] # If common subsequence is found, # increment its frequency if (t in map.keys()): map[t] += 1; else: map[t] = 1 res = 0 for a in map: # traversing the map # if frequency equals 1 if (map[a] == 1): res = max(res, len(a)) return res # Driver Codea = \"abcdabcd\"b = \"abcabc\" # input stringsprint(findLUSlength(a, b)) # This code is contributed by Mohit Kumar",
"e": 5020,
"s": 3853,
"text": null
},
{
"code": "// C# program to find longest// uncommon subsequence using// naive methodusing System;using System.Collections.Generic; class GFG{ // function to calculate // length of longest // uncommon subsequence static int findLUSlength(string a, string b) { // creating an unordered // map to map strings to // their frequency Dictionary<string, int> map = new Dictionary<string, int>(); List<string> strArr = new List<string>(); strArr.Add(a); strArr.Add(b); // traversing all elements // of vector strArr foreach (string s in strArr) { // Creating all possible // subsequences, i.e 2^n for (int i = 0; i < (1 << s.Length); i++) { string t = \"\"; for (int j = 0; j < s.Length; j++) { // ((i>>j) & 1) determines // which character goes // into string t if (((i >> j) & 1) != 0) t += s[j]; } // If common subsequence // is found, increment // its frequency if (map.ContainsKey(t)) { int value = map[t] + 1; map.Remove(t); map.Add(t, value); } else map.Add(t, 1); } } int res = 0; foreach (KeyValuePair<string, int> entry in map) // traversing the map { // if frequency equals 1 if (entry.Value == 1) res = Math.Max(res, entry.Key.Length); } return res; } // Driver code static void Main () { // input strings string a = \"abcdabcd\", b = \"abcabc\"; Console.Write(findLUSlength(a, b)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 7176,
"s": 5020,
"text": null
},
{
"code": "<script> // JavaScript program to find longest uncommon// subsequence using naive method // function to calculate length of// longest uncommon subsequence function findLUSlength(a,b) { // creating an unordered map to map // strings to their frequency let map= new Map(); let strArr= []; strArr.push(a); strArr.push(b); // traversing all elements of vector strArr for (let s=0; s<strArr.length;s++) { // Creating all possible subsequences, i.e 2^n for (let i = 0; i < (1 << strArr[s].length); i++) { let t = \"\"; for (let j = 0; j < strArr[s].length; j++) { // ((i>>j) & 1) determines which // character goes into string t if (((i >> j) & 1) != 0) t += strArr[s][j]; } // If common subsequence is found, // increment its frequency if (map.has(t)) map.set(t,map.get(t)+1); else map.set(t,1); } } let res = 0; for (let [key, value] of map.entries()) // traversing the map { // if frequency equals 1 if (value == 1) res = Math.max(res, key.length); } return res; } // Driver code // input strings let a = \"abcdabcd\", b = \"abcabc\"; document.write(findLUSlength(a, b)); // This code is contributed by unknown2108 </script>",
"e": 8662,
"s": 7176,
"text": null
},
{
"code": null,
"e": 8672,
"s": 8662,
"text": "Output: "
},
{
"code": null,
"e": 8674,
"s": 8672,
"text": "8"
},
{
"code": null,
"e": 8751,
"s": 8676,
"text": "Time complexity: O(2x + 2y), where x and y are the lengths of two strings."
},
{
"code": null,
"e": 8781,
"s": 8751,
"text": "Auxiliary Space : O(2x + 2y)."
},
{
"code": null,
"e": 8935,
"s": 8781,
"text": "Efficient Algorithm: If we analyze the problem carefully, it would seem much easier than it looks. All the three possible cases are as described below; "
},
{
"code": null,
"e": 9496,
"s": 8935,
"text": "If both the strings are identical, for example: “ac” and “ac”, it is obvious that no subsequence will be uncommon. Hence, return 0.If length(a) = length(b) and a ? b, for example: “abcdef” and “defghi”, out of these two strings one string will never be a subsequence of other string. Hence, return length(a) or length(b).If length(a) ? length(b), for example: “abcdabcd” and “abcabc”, in this case we can consider bigger string as a required subsequence because bigger string can not be a subsequence of smaller string. Hence, return max(length(a), length(b))."
},
{
"code": null,
"e": 9628,
"s": 9496,
"text": "If both the strings are identical, for example: “ac” and “ac”, it is obvious that no subsequence will be uncommon. Hence, return 0."
},
{
"code": null,
"e": 9819,
"s": 9628,
"text": "If length(a) = length(b) and a ? b, for example: “abcdef” and “defghi”, out of these two strings one string will never be a subsequence of other string. Hence, return length(a) or length(b)."
},
{
"code": null,
"e": 10059,
"s": 9819,
"text": "If length(a) ? length(b), for example: “abcdabcd” and “abcabc”, in this case we can consider bigger string as a required subsequence because bigger string can not be a subsequence of smaller string. Hence, return max(length(a), length(b))."
},
{
"code": null,
"e": 10065,
"s": 10061,
"text": "C++"
},
{
"code": null,
"e": 10070,
"s": 10065,
"text": "Java"
},
{
"code": null,
"e": 10078,
"s": 10070,
"text": "Python3"
},
{
"code": null,
"e": 10081,
"s": 10078,
"text": "C#"
},
{
"code": null,
"e": 10085,
"s": 10081,
"text": "PHP"
},
{
"code": null,
"e": 10096,
"s": 10085,
"text": "Javascript"
},
{
"code": "// CPP Program to find longest uncommon// subsequence.#include <iostream>using namespace std; // function to calculate length of longest// uncommon subsequenceint findLUSlength(string a, string b){ // Case 1: If strings are equal if (!a.compare(b)) return 0; // for case 2 and case 3 return max(a.length(), b.length());} // Driver codeint main(){ string a = \"abcdabcd\", b = \"abcabc\"; cout << findLUSlength(a, b); return 0;}",
"e": 10550,
"s": 10096,
"text": null
},
{
"code": "// Java program to find longest uncommon// subsequence using naive method import java.io.*;import java.util.*; class GfG{ // function to calculate length of longest// uncommon subsequencestatic int findLUSlength(String a, String b){ // Case 1: If strings are equal if (a.equals(b)==true) return 0; // for case 2 and case 3 return Math.max(a.length(), b.length());} // Driver code public static void main (String[] args) { // input strings String a = \"abcdabcd\", b = \"abcabc\"; System.out.println(findLUSlength(a, b)); }} // This code is contributed by Gitanjali.",
"e": 11162,
"s": 10550,
"text": null
},
{
"code": "# Python program to find# longest uncommon# subsequence using naive method import math # function to calculate# length of longest# uncommon subsequencedef findLUSlength( a, b): # Case 1: If strings are equal if (a==b) : return 0 # for case 2 and case 3 return max(len(a), len(b)) # Driver code #input stringsa = \"abcdabcd\"b = \"abcabc\"print (findLUSlength(a, b)) # This code is contributed by Gitanjali.",
"e": 11588,
"s": 11162,
"text": null
},
{
"code": "// C# program to find longest uncommon// subsequence using naive method.using System; class GfG { // function to calculate length // of longest uncommon subsequence static int findLUSlength(String a, String b) { // Case 1: If strings are equal if (a.Equals(b)==true) return 0; // for case 2 and case 3 return Math.Max(a.Length, b.Length); } // Driver code public static void Main () { // input strings String a = \"abcdabcd\", b = \"abcabc\"; Console.Write(findLUSlength(a, b)); }} // This code is contributed by nitin mittal.",
"e": 12223,
"s": 11588,
"text": null
},
{
"code": "<?php// PHP Program to find longest// uncommon subsequence. // function to calculate length// of longest uncommon subsequencefunction findLUSlength($a, $b){ // Case 1: If strings // are equal if (!strcmp($a, $b)) return 0; // for case 2 // and case 3 return max(strlen($a), strlen($b));} // Driver code$a = \"abcdabcd\";$b = \"abcabc\";echo (findLUSlength($a, $b)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 12685,
"s": 12223,
"text": null
},
{
"code": "<script> // JavaScript Program to find longest uncommon// subsequence. // function to calculate length of longest// uncommon subsequencefunction findLUSlength(a, b){ // Case 1: If strings are equal if (a===b) return 0; // for case 2 and case 3 return Math.max(a.length, b.length);} // Driver codevar a = \"abcdabcd\", b = \"abcabc\";document.write( findLUSlength(a, b)); </script>",
"e": 13083,
"s": 12685,
"text": null
},
{
"code": null,
"e": 13093,
"s": 13083,
"text": "Output: "
},
{
"code": null,
"e": 13095,
"s": 13093,
"text": "8"
},
{
"code": null,
"e": 13118,
"s": 13095,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 13195,
"s": 13118,
"text": "Time complexity: O(min(x, y)), where x and y are the lengths of two strings."
},
{
"code": null,
"e": 13218,
"s": 13195,
"text": "Auxiliary Space: O(1)."
},
{
"code": null,
"e": 13233,
"s": 13220,
"text": "nitin mittal"
},
{
"code": null,
"e": 13245,
"s": 13233,
"text": "manishshaw1"
},
{
"code": null,
"e": 13260,
"s": 13245,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 13272,
"s": 13260,
"text": "unknown2108"
},
{
"code": null,
"e": 13281,
"s": 13272,
"text": "noob2000"
},
{
"code": null,
"e": 13293,
"s": 13281,
"text": "subsequence"
},
{
"code": null,
"e": 13301,
"s": 13293,
"text": "Strings"
},
{
"code": null,
"e": 13309,
"s": 13301,
"text": "Strings"
},
{
"code": null,
"e": 13407,
"s": 13309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13452,
"s": 13407,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 13516,
"s": 13452,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 13561,
"s": 13516,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 13596,
"s": 13561,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 13661,
"s": 13596,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 13690,
"s": 13661,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 13751,
"s": 13690,
"text": "Find if a string is interleaved of two other strings | DP-33"
},
{
"code": null,
"e": 13803,
"s": 13751,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 13860,
"s": 13803,
"text": "Check if an URL is valid or not using Regular Expression"
}
]
|
Bootstrap 4 .d-*-flex class | Use the .d-*-flex class in Bootstrap to set a flexbox container on a screen size as shown below −
<div class="d-flex bg-primary">d-flex</div>
<span class="d-sm-flex bg-warning">d-sm-flex</span>
<span class="d-md-flex bg-info">d-md-flex</span>
<span class="d-lg-flex bg-success">d-lg-flex</span>
Above the flex is set for different screen sizes, for example,
Let us see an example of the class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h2>Understanding Flex</h2>
<div class="d-flex bg-primary">d-flex</div>
<span class="d-sm-flex bg-warning">Small Screen Size</span>
<span class="d-md-flex bg-info"> Medium Screen Size </span>
<span class="d-lg-flex bg-success"> Large Screen Size </span>
<span class="d-xl-flex bg-danger"> Extra Large Screen Size </span>
</div>
</body>
</html> | [
{
"code": null,
"e": 1285,
"s": 1187,
"text": "Use the .d-*-flex class in Bootstrap to set a flexbox container on a screen size as shown below −"
},
{
"code": null,
"e": 1482,
"s": 1285,
"text": "<div class=\"d-flex bg-primary\">d-flex</div>\n<span class=\"d-sm-flex bg-warning\">d-sm-flex</span>\n<span class=\"d-md-flex bg-info\">d-md-flex</span>\n<span class=\"d-lg-flex bg-success\">d-lg-flex</span>"
},
{
"code": null,
"e": 1545,
"s": 1482,
"text": "Above the flex is set for different screen sizes, for example,"
},
{
"code": null,
"e": 1582,
"s": 1545,
"text": "Let us see an example of the class −"
},
{
"code": null,
"e": 1592,
"s": 1582,
"text": "Live Demo"
},
{
"code": null,
"e": 2470,
"s": 1592,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n<div class=\"container mt-3\">\n <h2>Understanding Flex</h2>\n <div class=\"d-flex bg-primary\">d-flex</div>\n <span class=\"d-sm-flex bg-warning\">Small Screen Size</span>\n <span class=\"d-md-flex bg-info\"> Medium Screen Size </span>\n <span class=\"d-lg-flex bg-success\"> Large Screen Size </span>\n <span class=\"d-xl-flex bg-danger\"> Extra Large Screen Size </span>\n</div>\n\n</body>\n</html>"
}
]
|
Relation Schema in DBMS | 06 Aug, 2021
Relation schema defines the design and structure of the relation like it consists of the relation name, set of attributes/field names/column names. every attribute would have an associated domain.
There is a student named Geeks, she is pursuing B.Tech, in the 4th year, and belongs to IT department (department no. 1) and has roll number 1601347 She is proctored by Mrs. S Mohanty. If we want to represent this using databases we would have to create a student table with name, sex, degree, year, department, department number, roll number and proctor (adviser) as the attributes.
student (rollNo, name, degree, year, sex, deptNo, advisor)
Note – If we create a database, details of other students can also be recorded.
Similarly, we have the IT Department, with department Id 1, having Mrs. Sujata Chakravarty as the head of department. And we can call the department on the number 0657 228662 .
This and other departments can be represented by the department table, having department ID, name, hod and phone as attributes.
department (deptId, name, hod, phone)
The course that a student has selected has a courseid, course name, credit and department number.
course (coursId, ename, credits, deptNo)
The professor would have an employee Id, name, sex, department no. and phone number.
professor (empId, name, sex, startYear, deptNo, phone)
We can have another table named enrollment, which has roll no, courseId, semester, year and grade as the attributes.
enrollment (rollNo, coursId, sem, year, grade)
Teaching can be another table, having employee id, course id, semester, year and classroom as attributes.
teaching (empId, coursed, sem, year, Classroom)
When we start courses, there are some courses which another course that needs to be completed before starting the current course, so this can be represented by the Prerequisite table having prerequisite course and course id attributes.
prerequisite (preReqCourse, courseId)
The relations between them is represented through arrows in the following Relation diagram,
This represents that the deptNo in student table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. This represents that the advisor in student table is a foreign key. It refers to empId in professor table. This represents that the hod in department table is a foreign key. It refers to empId in professor table. This represents that the deptNo in course table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. This represents that the rollNo in enrollment table is same as rollNo used in student table. This represents that the courseId in enrollment table is same as courseId used in course table. This represents that the courseId in teaching table is same as courseId used in course table. This represents that the empId in teaching table is same as empId used in professor table. This represents that preReqCourse in prerequisite table is a foreign key. It refers to courseId in course table. This represents that the deptNo in student table is same as deptId used in department table.
This represents that the deptNo in student table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table.
This represents that the advisor in student table is a foreign key. It refers to empId in professor table.
This represents that the hod in department table is a foreign key. It refers to empId in professor table.
This represents that the deptNo in course table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table.
This represents that the rollNo in enrollment table is same as rollNo used in student table.
This represents that the courseId in enrollment table is same as courseId used in course table.
This represents that the courseId in teaching table is same as courseId used in course table.
This represents that the empId in teaching table is same as empId used in professor table.
This represents that preReqCourse in prerequisite table is a foreign key. It refers to courseId in course table.
This represents that the deptNo in student table is same as deptId used in department table.
Note – startYear in professor table is same as year in student table
abhishek0719kadiyan
DBMS
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
OLAP Guidelines (Codd's Rule)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 251,
"s": 53,
"text": "Relation schema defines the design and structure of the relation like it consists of the relation name, set of attributes/field names/column names. every attribute would have an associated domain. "
},
{
"code": null,
"e": 637,
"s": 251,
"text": "There is a student named Geeks, she is pursuing B.Tech, in the 4th year, and belongs to IT department (department no. 1) and has roll number 1601347 She is proctored by Mrs. S Mohanty. If we want to represent this using databases we would have to create a student table with name, sex, degree, year, department, department number, roll number and proctor (adviser) as the attributes. "
},
{
"code": null,
"e": 696,
"s": 637,
"text": "student (rollNo, name, degree, year, sex, deptNo, advisor)"
},
{
"code": null,
"e": 777,
"s": 696,
"text": "Note – If we create a database, details of other students can also be recorded. "
},
{
"code": null,
"e": 955,
"s": 777,
"text": "Similarly, we have the IT Department, with department Id 1, having Mrs. Sujata Chakravarty as the head of department. And we can call the department on the number 0657 228662 . "
},
{
"code": null,
"e": 1083,
"s": 955,
"text": "This and other departments can be represented by the department table, having department ID, name, hod and phone as attributes."
},
{
"code": null,
"e": 1121,
"s": 1083,
"text": "department (deptId, name, hod, phone)"
},
{
"code": null,
"e": 1221,
"s": 1121,
"text": "The course that a student has selected has a courseid, course name, credit and department number. "
},
{
"code": null,
"e": 1262,
"s": 1221,
"text": "course (coursId, ename, credits, deptNo)"
},
{
"code": null,
"e": 1348,
"s": 1262,
"text": "The professor would have an employee Id, name, sex, department no. and phone number. "
},
{
"code": null,
"e": 1403,
"s": 1348,
"text": "professor (empId, name, sex, startYear, deptNo, phone)"
},
{
"code": null,
"e": 1521,
"s": 1403,
"text": "We can have another table named enrollment, which has roll no, courseId, semester, year and grade as the attributes. "
},
{
"code": null,
"e": 1568,
"s": 1521,
"text": "enrollment (rollNo, coursId, sem, year, grade)"
},
{
"code": null,
"e": 1675,
"s": 1568,
"text": "Teaching can be another table, having employee id, course id, semester, year and classroom as attributes. "
},
{
"code": null,
"e": 1723,
"s": 1675,
"text": "teaching (empId, coursed, sem, year, Classroom)"
},
{
"code": null,
"e": 1961,
"s": 1723,
"text": "When we start courses, there are some courses which another course that needs to be completed before starting the current course, so this can be represented by the Prerequisite table having prerequisite course and course id attributes. "
},
{
"code": null,
"e": 2000,
"s": 1961,
"text": "prerequisite (preReqCourse, courseId) "
},
{
"code": null,
"e": 2094,
"s": 2000,
"text": "The relations between them is represented through arrows in the following Relation diagram, "
},
{
"code": null,
"e": 3263,
"s": 2096,
"text": "This represents that the deptNo in student table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. This represents that the advisor in student table is a foreign key. It refers to empId in professor table. This represents that the hod in department table is a foreign key. It refers to empId in professor table. This represents that the deptNo in course table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. This represents that the rollNo in enrollment table is same as rollNo used in student table. This represents that the courseId in enrollment table is same as courseId used in course table. This represents that the courseId in teaching table is same as courseId used in course table. This represents that the empId in teaching table is same as empId used in professor table. This represents that preReqCourse in prerequisite table is a foreign key. It refers to courseId in course table. This represents that the deptNo in student table is same as deptId used in department table. "
},
{
"code": null,
"e": 3447,
"s": 3263,
"text": "This represents that the deptNo in student table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. "
},
{
"code": null,
"e": 3556,
"s": 3447,
"text": "This represents that the advisor in student table is a foreign key. It refers to empId in professor table. "
},
{
"code": null,
"e": 3664,
"s": 3556,
"text": "This represents that the hod in department table is a foreign key. It refers to empId in professor table. "
},
{
"code": null,
"e": 3847,
"s": 3664,
"text": "This represents that the deptNo in course table table is same as deptId used in department table. deptNo in student table is a foreign key. It refers to deptId in department table. "
},
{
"code": null,
"e": 3942,
"s": 3847,
"text": "This represents that the rollNo in enrollment table is same as rollNo used in student table. "
},
{
"code": null,
"e": 4040,
"s": 3942,
"text": "This represents that the courseId in enrollment table is same as courseId used in course table. "
},
{
"code": null,
"e": 4136,
"s": 4040,
"text": "This represents that the courseId in teaching table is same as courseId used in course table. "
},
{
"code": null,
"e": 4229,
"s": 4136,
"text": "This represents that the empId in teaching table is same as empId used in professor table. "
},
{
"code": null,
"e": 4344,
"s": 4229,
"text": "This represents that preReqCourse in prerequisite table is a foreign key. It refers to courseId in course table. "
},
{
"code": null,
"e": 4439,
"s": 4344,
"text": "This represents that the deptNo in student table is same as deptId used in department table. "
},
{
"code": null,
"e": 4509,
"s": 4439,
"text": "Note – startYear in professor table is same as year in student table "
},
{
"code": null,
"e": 4529,
"s": 4509,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 4534,
"s": 4529,
"text": "DBMS"
},
{
"code": null,
"e": 4542,
"s": 4534,
"text": "GATE CS"
},
{
"code": null,
"e": 4546,
"s": 4542,
"text": "SQL"
},
{
"code": null,
"e": 4551,
"s": 4546,
"text": "DBMS"
},
{
"code": null,
"e": 4555,
"s": 4551,
"text": "SQL"
},
{
"code": null,
"e": 4653,
"s": 4555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4694,
"s": 4653,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 4731,
"s": 4694,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 4761,
"s": 4731,
"text": "OLAP Guidelines (Codd's Rule)"
},
{
"code": null,
"e": 4802,
"s": 4761,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 4834,
"s": 4802,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 4854,
"s": 4834,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 4867,
"s": 4854,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 4894,
"s": 4867,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 4943,
"s": 4894,
"text": "Page Replacement Algorithms in Operating Systems"
}
]
|
Python – Import module from different directory | 28 Apr, 2021
While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory.
Note: A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package.
Let’s suppose, we have two different folders, one contains main.py which is our main Python file where we want to import module1 from Folder_2.
Directory Structure
- Folder_1
- main.py
- Folder_2
- module1.py
Module1 contains two functions called add and odd_even. The function add will takes two arguments and return the addition of them. The odd_even function will take only one argument and print Even if the number is even or print Odd if the number is odd.
Python3
# creating a simple add functiondef add(a, b): return a+b # creating a simple odd_even function# to check if the number is odd or evendef odd_even(n): if n % 2 == 0: print("Even") else: print("Odd")
If we simply try to import module1 from Folder_2, we will be encountering the following error.
Python3
# importing module1 from another folderimport Folder_2 # calling odd_even functionmodule1.odd_even(5)
Output:
Error
ModuleNotFoundError, because by default python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.
We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that python can also look for the module in that directory if it doesn’t found the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.
Python3
# importing sysimport sys # adding Folder_2 to the system pathsys.path.insert(0, '/home/amninder/Desktop/Folder_2') # importing the add and odd_even # functionfrom module1 import odd_even, add # calling odd_even functionodd_even(5) # calling add functionprint("Addition of two number is :", add(2, 2))
Output:
Using sys
Similarly, if you don’t want to use the sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.
In Linux, we can use the following command in the terminal to set the path:
export PYTHONPATH=’path/to/directory’
In Windows system :
SET PYTHONPATH=”path/to/directory”
To see if PYTHONPATH variable holds the path of the new folder, we can use the following command:
echo $PYTHONPATH
Python3
# importing the add and odd_even functionfrom module1 import odd_even, add # calling odd_even functionodd_even(5) # calling add functionprint("Addition of two number is :", add(2, 2))
Output:
Using PYTHONPATH
Suppose we have a directory structure like this:
- project
- Folder_1
- main.py
- Folder_2
- subfolder
- new.py
Now, you want to import the new.py module from Folder_2 to our project’s Folder_1 main.py file.
Syntax:
from project.folder.subfolder.filename import functionname
Python3
# importing sysimport sys # adding Folder_2/subfolder to the system pathsys.path.insert(0, '/home/amninder/Desktop/project/Folder_2/subfolder') # importing the hellofrom new import hello # calling hello functionhello()
Output:
Output
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 375,
"s": 54,
"text": "While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory."
},
{
"code": null,
"e": 499,
"s": 375,
"text": "Note: A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package."
},
{
"code": null,
"e": 644,
"s": 499,
"text": "Let’s suppose, we have two different folders, one contains main.py which is our main Python file where we want to import module1 from Folder_2. "
},
{
"code": null,
"e": 664,
"s": 644,
"text": "Directory Structure"
},
{
"code": null,
"e": 720,
"s": 664,
"text": " - Folder_1\n - main.py\n - Folder_2\n - module1.py"
},
{
"code": null,
"e": 973,
"s": 720,
"text": "Module1 contains two functions called add and odd_even. The function add will takes two arguments and return the addition of them. The odd_even function will take only one argument and print Even if the number is even or print Odd if the number is odd."
},
{
"code": null,
"e": 981,
"s": 973,
"text": "Python3"
},
{
"code": "# creating a simple add functiondef add(a, b): return a+b # creating a simple odd_even function# to check if the number is odd or evendef odd_even(n): if n % 2 == 0: print(\"Even\") else: print(\"Odd\")",
"e": 1204,
"s": 981,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1204,
"text": "If we simply try to import module1 from Folder_2, we will be encountering the following error."
},
{
"code": null,
"e": 1307,
"s": 1299,
"text": "Python3"
},
{
"code": "# importing module1 from another folderimport Folder_2 # calling odd_even functionmodule1.odd_even(5)",
"e": 1410,
"s": 1307,
"text": null
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Output:"
},
{
"code": null,
"e": 1424,
"s": 1418,
"text": "Error"
},
{
"code": null,
"e": 1703,
"s": 1424,
"text": "ModuleNotFoundError, because by default python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail."
},
{
"code": null,
"e": 2067,
"s": 1703,
"text": "We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that python can also look for the module in that directory if it doesn’t found the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path."
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Python3"
},
{
"code": "# importing sysimport sys # adding Folder_2 to the system pathsys.path.insert(0, '/home/amninder/Desktop/Folder_2') # importing the add and odd_even # functionfrom module1 import odd_even, add # calling odd_even functionodd_even(5) # calling add functionprint(\"Addition of two number is :\", add(2, 2))",
"e": 2381,
"s": 2075,
"text": null
},
{
"code": null,
"e": 2389,
"s": 2381,
"text": "Output:"
},
{
"code": null,
"e": 2399,
"s": 2389,
"text": "Using sys"
},
{
"code": null,
"e": 2584,
"s": 2399,
"text": "Similarly, if you don’t want to use the sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working. "
},
{
"code": null,
"e": 2660,
"s": 2584,
"text": "In Linux, we can use the following command in the terminal to set the path:"
},
{
"code": null,
"e": 2698,
"s": 2660,
"text": "export PYTHONPATH=’path/to/directory’"
},
{
"code": null,
"e": 2718,
"s": 2698,
"text": "In Windows system :"
},
{
"code": null,
"e": 2753,
"s": 2718,
"text": "SET PYTHONPATH=”path/to/directory”"
},
{
"code": null,
"e": 2851,
"s": 2753,
"text": "To see if PYTHONPATH variable holds the path of the new folder, we can use the following command:"
},
{
"code": null,
"e": 2868,
"s": 2851,
"text": "echo $PYTHONPATH"
},
{
"code": null,
"e": 2876,
"s": 2868,
"text": "Python3"
},
{
"code": "# importing the add and odd_even functionfrom module1 import odd_even, add # calling odd_even functionodd_even(5) # calling add functionprint(\"Addition of two number is :\", add(2, 2))",
"e": 3062,
"s": 2876,
"text": null
},
{
"code": null,
"e": 3070,
"s": 3062,
"text": "Output:"
},
{
"code": null,
"e": 3087,
"s": 3070,
"text": "Using PYTHONPATH"
},
{
"code": null,
"e": 3136,
"s": 3087,
"text": "Suppose we have a directory structure like this:"
},
{
"code": null,
"e": 3235,
"s": 3136,
"text": "- project\n - Folder_1\n - main.py\n - Folder_2\n - subfolder\n - new.py"
},
{
"code": null,
"e": 3331,
"s": 3235,
"text": "Now, you want to import the new.py module from Folder_2 to our project’s Folder_1 main.py file."
},
{
"code": null,
"e": 3339,
"s": 3331,
"text": "Syntax:"
},
{
"code": null,
"e": 3399,
"s": 3339,
"text": " from project.folder.subfolder.filename import functionname"
},
{
"code": null,
"e": 3407,
"s": 3399,
"text": "Python3"
},
{
"code": "# importing sysimport sys # adding Folder_2/subfolder to the system pathsys.path.insert(0, '/home/amninder/Desktop/project/Folder_2/subfolder') # importing the hellofrom new import hello # calling hello functionhello()",
"e": 3629,
"s": 3407,
"text": null
},
{
"code": null,
"e": 3637,
"s": 3629,
"text": "Output:"
},
{
"code": null,
"e": 3644,
"s": 3637,
"text": "Output"
},
{
"code": null,
"e": 3651,
"s": 3644,
"text": "Picked"
},
{
"code": null,
"e": 3666,
"s": 3651,
"text": "python-modules"
},
{
"code": null,
"e": 3673,
"s": 3666,
"text": "Python"
}
]
|
MultiMap in Java Guava | 10 Jul, 2020
Introduction : A Multimap is a general way to associate keys with arbitrarily many values. Guava’s Multimap framework makes it easy to handle a mapping from keys to multiple values. There are two ways to think of a Multimap conceptually :1) As a collection of mappings from single keys to single values.
a -> 1
a -> 2
a -> 4
b -> 3
c -> 5
2) As a mapping from unique keys to collections of values.
a -> [1, 2, 4]
b -> [3]
c -> [5]
Declaration : The declaration of com.google.common.collect.Multimap<K, V> interface is as :
@GwtCompatible
public interface Multimap
Below given is the list of some methods provided by Guava’s Multimap Interface :Views : Multimap also supports a number of powerful views. Much of the power of the multimap API comes from the view collections it provides. These always reflect the latest state of the multimap itself.
asMap views any Multimap<K, V> as a Map<K, Collection<V>>. The returned map supports remove, and changes to the returned collections write through, but the map does not support put or putAll.
entries views the Collection<Map.Entry<K, V>> of all entries in the Multimap. (For a SetMultimap, this is a Set.)
keySet views the distinct keys in the Multimap as a Set.
keys views the keys of the Multimap as a Multiset, with multiplicity equal to the number of values associated to that key. Elements can be removed from the Multiset, but not added, changes will write through.
values() views all the values in the Multimap as a “flattened” Collection<V>, all as one collection. This is similar to Iterables.concat(multimap.asMap().values()), but returns a full Collection instead.
Some other methods provided by Guava’s Multimap Interface are :
Multimap V/s Map : A Multimap<K, V> is not a Map<K, Collection<V>>, though such a map might be used in a Multimap implementation. Below given are the differences :
Multimap.get(key) always returns a non-null, possibly empty collection. This doesn’t imply that the multimap spends any memory associated with the key, but instead, the returned collection is a view that allows you to add associations with the key if you like.
If you prefer the more Map-like behavior of returning null for keys that aren’t in the multimap, use the asMap() view to get a Map<K, Collection<V>>.
Multimap.containsKey(key) is true if and only if there are any elements associated with the specified key. In particular, if a key k was previously associated with one or more values which have since been removed from the multimap, Multimap.containsKey(k) will return false.
Multimap.entries() returns all entries for all keys in the Multimap. If you want all key-collection entries, use asMap().entrySet().
Multimap.size() returns the number of entries in the entire multimap, not the number of distinct keys. Use Multimap.keySet().size() instead to get the number of distinct keys.
Implementations : Multimap provides a wide variety of implementations. You can use it in most places you would have used a Map<K, Collection<V>>.
Advantages : Multimaps are commonly used in places where a Map<K, Collection<V>> would otherwise have appeared.
There is no need to populate an empty collection before adding an entry with put().
The get() method never returns null, only an empty collection (we do not need to check against null like in Map<String, Collection<V>> test case).
A key is contained in the Multimap if and only if it maps to at least one value. Any operation that causes a key to has zero associated values, has the effect of removing that key from the Multimap.
The total entry values count is available as size().
References :Google Guava
java-guava
java-map
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
How to add an element to an Array in Java?
Stack Class in Java
PriorityQueue in Java
Math pow() method in Java with Example
Initialize an ArrayList in Java
List Interface in Java with Examples
ArrayList in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "Introduction : A Multimap is a general way to associate keys with arbitrarily many values. Guava’s Multimap framework makes it easy to handle a mapping from keys to multiple values. There are two ways to think of a Multimap conceptually :1) As a collection of mappings from single keys to single values."
},
{
"code": null,
"e": 394,
"s": 358,
"text": "a -> 1\na -> 2\na -> 4\nb -> 3\nc -> 5\n"
},
{
"code": null,
"e": 453,
"s": 394,
"text": "2) As a mapping from unique keys to collections of values."
},
{
"code": null,
"e": 488,
"s": 453,
"text": "a -> [1, 2, 4]\nb -> [3]\nc -> [5] \n"
},
{
"code": null,
"e": 580,
"s": 488,
"text": "Declaration : The declaration of com.google.common.collect.Multimap<K, V> interface is as :"
},
{
"code": null,
"e": 622,
"s": 580,
"text": "@GwtCompatible\npublic interface Multimap\n"
},
{
"code": null,
"e": 906,
"s": 622,
"text": "Below given is the list of some methods provided by Guava’s Multimap Interface :Views : Multimap also supports a number of powerful views. Much of the power of the multimap API comes from the view collections it provides. These always reflect the latest state of the multimap itself."
},
{
"code": null,
"e": 1098,
"s": 906,
"text": "asMap views any Multimap<K, V> as a Map<K, Collection<V>>. The returned map supports remove, and changes to the returned collections write through, but the map does not support put or putAll."
},
{
"code": null,
"e": 1212,
"s": 1098,
"text": "entries views the Collection<Map.Entry<K, V>> of all entries in the Multimap. (For a SetMultimap, this is a Set.)"
},
{
"code": null,
"e": 1269,
"s": 1212,
"text": "keySet views the distinct keys in the Multimap as a Set."
},
{
"code": null,
"e": 1478,
"s": 1269,
"text": "keys views the keys of the Multimap as a Multiset, with multiplicity equal to the number of values associated to that key. Elements can be removed from the Multiset, but not added, changes will write through."
},
{
"code": null,
"e": 1682,
"s": 1478,
"text": "values() views all the values in the Multimap as a “flattened” Collection<V>, all as one collection. This is similar to Iterables.concat(multimap.asMap().values()), but returns a full Collection instead."
},
{
"code": null,
"e": 1746,
"s": 1682,
"text": "Some other methods provided by Guava’s Multimap Interface are :"
},
{
"code": null,
"e": 1910,
"s": 1746,
"text": "Multimap V/s Map : A Multimap<K, V> is not a Map<K, Collection<V>>, though such a map might be used in a Multimap implementation. Below given are the differences :"
},
{
"code": null,
"e": 2171,
"s": 1910,
"text": "Multimap.get(key) always returns a non-null, possibly empty collection. This doesn’t imply that the multimap spends any memory associated with the key, but instead, the returned collection is a view that allows you to add associations with the key if you like."
},
{
"code": null,
"e": 2321,
"s": 2171,
"text": "If you prefer the more Map-like behavior of returning null for keys that aren’t in the multimap, use the asMap() view to get a Map<K, Collection<V>>."
},
{
"code": null,
"e": 2596,
"s": 2321,
"text": "Multimap.containsKey(key) is true if and only if there are any elements associated with the specified key. In particular, if a key k was previously associated with one or more values which have since been removed from the multimap, Multimap.containsKey(k) will return false."
},
{
"code": null,
"e": 2729,
"s": 2596,
"text": "Multimap.entries() returns all entries for all keys in the Multimap. If you want all key-collection entries, use asMap().entrySet()."
},
{
"code": null,
"e": 2905,
"s": 2729,
"text": "Multimap.size() returns the number of entries in the entire multimap, not the number of distinct keys. Use Multimap.keySet().size() instead to get the number of distinct keys."
},
{
"code": null,
"e": 3051,
"s": 2905,
"text": "Implementations : Multimap provides a wide variety of implementations. You can use it in most places you would have used a Map<K, Collection<V>>."
},
{
"code": null,
"e": 3163,
"s": 3051,
"text": "Advantages : Multimaps are commonly used in places where a Map<K, Collection<V>> would otherwise have appeared."
},
{
"code": null,
"e": 3247,
"s": 3163,
"text": "There is no need to populate an empty collection before adding an entry with put()."
},
{
"code": null,
"e": 3394,
"s": 3247,
"text": "The get() method never returns null, only an empty collection (we do not need to check against null like in Map<String, Collection<V>> test case)."
},
{
"code": null,
"e": 3593,
"s": 3394,
"text": "A key is contained in the Multimap if and only if it maps to at least one value. Any operation that causes a key to has zero associated values, has the effect of removing that key from the Multimap."
},
{
"code": null,
"e": 3646,
"s": 3593,
"text": "The total entry values count is available as size()."
},
{
"code": null,
"e": 3671,
"s": 3646,
"text": "References :Google Guava"
},
{
"code": null,
"e": 3682,
"s": 3671,
"text": "java-guava"
},
{
"code": null,
"e": 3691,
"s": 3682,
"text": "java-map"
},
{
"code": null,
"e": 3696,
"s": 3691,
"text": "Java"
},
{
"code": null,
"e": 3701,
"s": 3696,
"text": "Java"
},
{
"code": null,
"e": 3799,
"s": 3701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3818,
"s": 3799,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3842,
"s": 3818,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 3874,
"s": 3842,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3917,
"s": 3874,
"text": "How to add an element to an Array in Java?"
},
{
"code": null,
"e": 3937,
"s": 3917,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3959,
"s": 3937,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 3998,
"s": 3959,
"text": "Math pow() method in Java with Example"
},
{
"code": null,
"e": 4030,
"s": 3998,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 4067,
"s": 4030,
"text": "List Interface in Java with Examples"
}
]
|
Angular Material - Tabs | The md-tabs and md-tab Angular directives are used to show tabs in the applcation. md-tabs is the grouping container for md-tab elements.
The following table lists out the parameters and description of the different attributes of md-tabs.
md-selected
Index of the active/selected tab.
md-no-ink
If present, disables the ink ripple effects.
md-no-ink-bar
If present, disables the selection ink bar.
md-align-tabs
Attribute to indicate position of tab buttons: bottom or top; default is top.
md-stretch-tabs
Attribute to indicate whether or not to stretch tabs: auto, always, or never; default is auto.
md-dynamic-height
When enabled, the tab wrapper will resize based on the contents of the selected tab.
md-center-tabs
When enabled, tabs will be centered provided there is no need for pagination.
md-no-pagination
When enabled, pagination will remain off.
md-swipe-content
When enabled, swipe gestures will be enabled for the content area to jump between tabs.
md-enable-disconnect
When enabled, scopes will be disconnected for tabs that are not being displayed. This provides a performance boost, but may also cause unexpected issues and is not recommended for most users.
md-autoselect
When present, any tabs added after the initial load will be automatically selected.
The following table lists out the parameters and description of the different attributes of md-tab.
label
Optional attribute to specify a simple string as the tab label.
ng-disabled
If present, disabled tab selection.
md-on-deselect
Expression to be evaluated after the tab is de-selected.
md-on-select
Expression to be evaluated after the tab is selected.
md-active
When true, sets the active tab.
Note − There can only be one active tab at a time.
The following example shows the use of md-tabs and also the uses of tabs components.
am_tabs.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('tabController', tabController);
function tabController ($scope) {
$scope.data = {
selectedIndex: 0,
secondLocked: true,
secondLabel: "2",
bottom: false
};
$scope.next = function() {
$scope.data.selectedIndex = Math.min($scope.data.selectedIndex + 1, 2) ;
};
$scope.previous = function() {
$scope.data.selectedIndex = Math.max($scope.data.selectedIndex - 1, 0);
};
}
</script>
</head>
<body ng-app = "firstApplication">
<div id = "tabContainer" ng-controller = "tabController as ctrl" ng-cloak>
<md-content class = "md-padding">
<md-tabs class = "md-accent" md-selected = "data.selectedIndex"
md-align-tabs = "{{data.bottom ? 'bottom' : 'top'}}">
<md-tab id = "tab1">
<md-tab-label>1</md-tab-label>
<md-tab-body>Item #1 <br/>selectedIndex = 0;</md-tab-body>
</md-tab>
<md-tab id = "tab2" ng-disabled = "data.secondLocked">
<md-tab-label>{{data.secondLabel}}</md-tab-label>
<md-tab-body>Item #2 <br/>selectedIndex = 1;</md-tab-body>
</md-tab>
<md-tab id = "tab3">
<md-tab-label>3</md-tab-label>
<md-tab-body>Item #3<br/>selected Index = 2;</md-tab-body>
</md-tab>
</md-tabs>
</md-content>
<div class = "md-padding" layout = "row" layout-sm = "column"
layout-align = "left center" style = "padding-top: 0;">
<md-checkbox ng-model = "data.secondLocked" aria-label = "Disable tab 2?"
style = "margin: 5px;">Disable tab 2?</md-checkbox>
<md-checkbox ng-model = "data.bottom" aria-label = "Align tabs to bottom?"
style = "margin: 5px;">Align tabs to bottom?</md-checkbox>
</div>
</div>
</body>
</html>
Verify the result. | [
{
"code": null,
"e": 2462,
"s": 2324,
"text": "The md-tabs and md-tab Angular directives are used to show tabs in the applcation. md-tabs is the grouping container for md-tab elements."
},
{
"code": null,
"e": 2563,
"s": 2462,
"text": "The following table lists out the parameters and description of the different attributes of md-tabs."
},
{
"code": null,
"e": 2575,
"s": 2563,
"text": "md-selected"
},
{
"code": null,
"e": 2609,
"s": 2575,
"text": "Index of the active/selected tab."
},
{
"code": null,
"e": 2619,
"s": 2609,
"text": "md-no-ink"
},
{
"code": null,
"e": 2664,
"s": 2619,
"text": "If present, disables the ink ripple effects."
},
{
"code": null,
"e": 2678,
"s": 2664,
"text": "md-no-ink-bar"
},
{
"code": null,
"e": 2722,
"s": 2678,
"text": "If present, disables the selection ink bar."
},
{
"code": null,
"e": 2736,
"s": 2722,
"text": "md-align-tabs"
},
{
"code": null,
"e": 2814,
"s": 2736,
"text": "Attribute to indicate position of tab buttons: bottom or top; default is top."
},
{
"code": null,
"e": 2830,
"s": 2814,
"text": "md-stretch-tabs"
},
{
"code": null,
"e": 2925,
"s": 2830,
"text": "Attribute to indicate whether or not to stretch tabs: auto, always, or never; default is auto."
},
{
"code": null,
"e": 2943,
"s": 2925,
"text": "md-dynamic-height"
},
{
"code": null,
"e": 3028,
"s": 2943,
"text": "When enabled, the tab wrapper will resize based on the contents of the selected tab."
},
{
"code": null,
"e": 3043,
"s": 3028,
"text": "md-center-tabs"
},
{
"code": null,
"e": 3121,
"s": 3043,
"text": "When enabled, tabs will be centered provided there is no need for pagination."
},
{
"code": null,
"e": 3138,
"s": 3121,
"text": "md-no-pagination"
},
{
"code": null,
"e": 3180,
"s": 3138,
"text": "When enabled, pagination will remain off."
},
{
"code": null,
"e": 3197,
"s": 3180,
"text": "md-swipe-content"
},
{
"code": null,
"e": 3285,
"s": 3197,
"text": "When enabled, swipe gestures will be enabled for the content area to jump between tabs."
},
{
"code": null,
"e": 3306,
"s": 3285,
"text": "md-enable-disconnect"
},
{
"code": null,
"e": 3498,
"s": 3306,
"text": "When enabled, scopes will be disconnected for tabs that are not being displayed. This provides a performance boost, but may also cause unexpected issues and is not recommended for most users."
},
{
"code": null,
"e": 3512,
"s": 3498,
"text": "md-autoselect"
},
{
"code": null,
"e": 3596,
"s": 3512,
"text": "When present, any tabs added after the initial load will be automatically selected."
},
{
"code": null,
"e": 3696,
"s": 3596,
"text": "The following table lists out the parameters and description of the different attributes of md-tab."
},
{
"code": null,
"e": 3702,
"s": 3696,
"text": "label"
},
{
"code": null,
"e": 3766,
"s": 3702,
"text": "Optional attribute to specify a simple string as the tab label."
},
{
"code": null,
"e": 3778,
"s": 3766,
"text": "ng-disabled"
},
{
"code": null,
"e": 3814,
"s": 3778,
"text": "If present, disabled tab selection."
},
{
"code": null,
"e": 3829,
"s": 3814,
"text": "md-on-deselect"
},
{
"code": null,
"e": 3886,
"s": 3829,
"text": "Expression to be evaluated after the tab is de-selected."
},
{
"code": null,
"e": 3899,
"s": 3886,
"text": "md-on-select"
},
{
"code": null,
"e": 3953,
"s": 3899,
"text": "Expression to be evaluated after the tab is selected."
},
{
"code": null,
"e": 3963,
"s": 3953,
"text": "md-active"
},
{
"code": null,
"e": 3995,
"s": 3963,
"text": "When true, sets the active tab."
},
{
"code": null,
"e": 4046,
"s": 3995,
"text": "Note − There can only be one active tab at a time."
},
{
"code": null,
"e": 4131,
"s": 4046,
"text": "The following example shows the use of md-tabs and also the uses of tabs components."
},
{
"code": null,
"e": 4143,
"s": 4131,
"text": "am_tabs.htm"
},
{
"code": null,
"e": 7256,
"s": 4143,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('tabController', tabController);\n\n function tabController ($scope) { \n $scope.data = {\n selectedIndex: 0,\n secondLocked: true,\n secondLabel: \"2\",\n bottom: false\n };\n \n $scope.next = function() {\n $scope.data.selectedIndex = Math.min($scope.data.selectedIndex + 1, 2) ;\n };\n \n $scope.previous = function() {\n $scope.data.selectedIndex = Math.max($scope.data.selectedIndex - 1, 0);\n };\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"tabContainer\" ng-controller = \"tabController as ctrl\" ng-cloak>\n <md-content class = \"md-padding\">\n <md-tabs class = \"md-accent\" md-selected = \"data.selectedIndex\"\n md-align-tabs = \"{{data.bottom ? 'bottom' : 'top'}}\">\n <md-tab id = \"tab1\">\n <md-tab-label>1</md-tab-label>\n <md-tab-body>Item #1 <br/>selectedIndex = 0;</md-tab-body>\n </md-tab>\n \n <md-tab id = \"tab2\" ng-disabled = \"data.secondLocked\">\n <md-tab-label>{{data.secondLabel}}</md-tab-label>\n <md-tab-body>Item #2 <br/>selectedIndex = 1;</md-tab-body>\n </md-tab>\n \n <md-tab id = \"tab3\">\n <md-tab-label>3</md-tab-label>\n <md-tab-body>Item #3<br/>selected Index = 2;</md-tab-body>\n </md-tab>\n </md-tabs>\n </md-content>\n \n <div class = \"md-padding\" layout = \"row\" layout-sm = \"column\"\n layout-align = \"left center\" style = \"padding-top: 0;\">\n <md-checkbox ng-model = \"data.secondLocked\" aria-label = \"Disable tab 2?\"\n style = \"margin: 5px;\">Disable tab 2?</md-checkbox>\n <md-checkbox ng-model = \"data.bottom\" aria-label = \"Align tabs to bottom?\"\n style = \"margin: 5px;\">Align tabs to bottom?</md-checkbox>\n </div>\n \n </div>\n </body>\n</html>"
}
]
|
Sorting Hash in Perl | 28 Dec, 2018
Prerequisite: Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. Let us consider an example to understand the concept of sorting the hash.
Example: Consider a hash with the names of the students in a class and with their average score. Here, the name of the students are the keys and their average scores are the values. Print this hash using foreach loop on the student names returned by the keys function.
# Perl program to demonstrate # the concept of hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # displaying the keys and values of Hash# using the foreach loop and keys function # output may be different each # time when you run the codeforeach my $name (keys %studentnames) { # printing the keys and values of hash printf "%-8s %s\n", $name, $studentnames{$name};}
Output:
Marty 16.5
Jason 25.2
Plato 39
Vivek 27
Socrates 29.5
Martha 14
Earl 31
Uri 19.6
Nitin 30
Note: The output may contain any random order depends on the system and the version of Perl.
Hashes can be sorted in many ways as follows:
Sorting the Hash according to the ASCII values of its keys: Generally, sorting is based on ASCII table. It means sorting will keep all the upper-case letters in front of all the lower-case letters. This is the default behavior of the sorting. The above example code is sorted according to the ASCII values of its keys.
Sorting the Hash according to the alphabetical order of its keys: Here, the keys are sorted alphabetically.Example:# Perl program to demonstrate # sorting of the hash according # alphabetical order of its keysuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting the hash according # alphabetical order of its keysforeach my $name (sort {lc $a cmp lc $b} keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}Output:Earl 31
Jason 25.2
Martha 14
Marty 16.5
Nitin 30
Plato 39
Socrates 29.5
Uri 19.6
Vivek 27
Example:
# Perl program to demonstrate # sorting of the hash according # alphabetical order of its keysuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting the hash according # alphabetical order of its keysforeach my $name (sort {lc $a cmp lc $b} keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}
Output:
Earl 31
Jason 25.2
Martha 14
Marty 16.5
Nitin 30
Plato 39
Socrates 29.5
Uri 19.6
Vivek 27
Sorting according to the values of Hash: You can also sort the hash according to the values of hash as follows:Example 1: Sorting the hash values according to the ASCII table.# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to ASCII code of values of Hashforeach my $name (sort values %studentnames) { say $name;}Output:14
16.5
19.6
25.2
27
29.5
30
31
39
Example 2: Sorting according to the numerical value of Values of hash as follows:# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to the numerical value of# Values of hashforeach my $name (sort {$a<=>$b} values %studentnames) { say $name;}Output:14
16.5
19.6
25.2
27
29.5
30
31
39
Example 1: Sorting the hash values according to the ASCII table.
# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to ASCII code of values of Hashforeach my $name (sort values %studentnames) { say $name;}
Output:
14
16.5
19.6
25.2
27
29.5
30
31
39
Example 2: Sorting according to the numerical value of Values of hash as follows:
# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to the numerical value of# Values of hashforeach my $name (sort {$a<=>$b} values %studentnames) { say $name;}
Output:
14
16.5
19.6
25.2
27
29.5
30
31
39
Sort the keys of the hash according to the values: You can also sort the keys of hash according to the given values.Example 1: In the below program, <=> is termed as the spaceship operator. If you will run the code again and again then you can notice the difference in the output. Sometimes you find Plato before the Nitin and vice-versa.# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # Sort the keys of the hash# according to the values# Here $a and $b are the # placeholder variable of sortforeach my $name (sort {$studentnames{$a} <=> $studentnames{$b}} keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}Output:Martha 14
Marty 16.5
Uri 19.6
Jason 25.2
Vivek 27
Socrates 29.5
Earl 31
Plato 45
Nitin 45
Example 2: To solve the above code, keys having the same values can be sorted according to the ASCII table as follows:# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # keys that have the same value # will be sorted according the # ASCII tableforeach my $name (sort { $studentnames{$a} <=> $studentnames{$b} or $a cmp $b } keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}Output:Martha 14
Marty 16.5
Uri 19.6
Jason 25.2
Vivek 27
Socrates 29.5
Earl 31
Nitin 45
Plato 45
Explanation: Here you can see the key Nitin and Plato are sorted according to the ASCII table. It doesn’t matter how many times you run the code, the output will remain the same.
Example 1: In the below program, <=> is termed as the spaceship operator. If you will run the code again and again then you can notice the difference in the output. Sometimes you find Plato before the Nitin and vice-versa.
# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # Sort the keys of the hash# according to the values# Here $a and $b are the # placeholder variable of sortforeach my $name (sort {$studentnames{$a} <=> $studentnames{$b}} keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}
Output:
Martha 14
Marty 16.5
Uri 19.6
Jason 25.2
Vivek 27
Socrates 29.5
Earl 31
Plato 45
Nitin 45
Example 2: To solve the above code, keys having the same values can be sorted according to the ASCII table as follows:
# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # keys that have the same value # will be sorted according the # ASCII tableforeach my $name (sort { $studentnames{$a} <=> $studentnames{$b} or $a cmp $b } keys %studentnames) { printf "%-8s %s\n", $name, $studentnames{$name};}
Output:
Martha 14
Marty 16.5
Uri 19.6
Jason 25.2
Vivek 27
Socrates 29.5
Earl 31
Nitin 45
Plato 45
Explanation: Here you can see the key Nitin and Plato are sorted according to the ASCII table. It doesn’t matter how many times you run the code, the output will remain the same.
Perl-hashes
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | ne operator
Perl | Opening and Reading a File
Perl | Writing to a File
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | Multidimensional Hashes
Perl | File Handling Introduction
Perl | Data Types
How to Install Perl on Windows? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2018"
},
{
"code": null,
"e": 56,
"s": 28,
"text": "Prerequisite: Perl | Hashes"
},
{
"code": null,
"e": 378,
"s": 56,
"text": "Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. Let us consider an example to understand the concept of sorting the hash."
},
{
"code": null,
"e": 647,
"s": 378,
"text": "Example: Consider a hash with the names of the students in a class and with their average score. Here, the name of the students are the keys and their average scores are the values. Print this hash using foreach loop on the student names returned by the keys function."
},
{
"code": "# Perl program to demonstrate # the concept of hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # displaying the keys and values of Hash# using the foreach loop and keys function # output may be different each # time when you run the codeforeach my $name (keys %studentnames) { # printing the keys and values of hash printf \"%-8s %s\\n\", $name, $studentnames{$name};}",
"e": 1217,
"s": 647,
"text": null
},
{
"code": null,
"e": 1225,
"s": 1217,
"text": "Output:"
},
{
"code": null,
"e": 1342,
"s": 1225,
"text": "Marty 16.5\nJason 25.2\nPlato 39\nVivek 27\nSocrates 29.5\nMartha 14\nEarl 31\nUri 19.6\nNitin 30\n"
},
{
"code": null,
"e": 1435,
"s": 1342,
"text": "Note: The output may contain any random order depends on the system and the version of Perl."
},
{
"code": null,
"e": 1481,
"s": 1435,
"text": "Hashes can be sorted in many ways as follows:"
},
{
"code": null,
"e": 1800,
"s": 1481,
"text": "Sorting the Hash according to the ASCII values of its keys: Generally, sorting is based on ASCII table. It means sorting will keep all the upper-case letters in front of all the lower-case letters. This is the default behavior of the sorting. The above example code is sorted according to the ASCII values of its keys."
},
{
"code": null,
"e": 2545,
"s": 1800,
"text": "Sorting the Hash according to the alphabetical order of its keys: Here, the keys are sorted alphabetically.Example:# Perl program to demonstrate # sorting of the hash according # alphabetical order of its keysuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting the hash according # alphabetical order of its keysforeach my $name (sort {lc $a cmp lc $b} keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}Output:Earl 31\nJason 25.2\nMartha 14\nMarty 16.5\nNitin 30\nPlato 39\nSocrates 29.5\nUri 19.6\nVivek 27\n"
},
{
"code": null,
"e": 2554,
"s": 2545,
"text": "Example:"
},
{
"code": "# Perl program to demonstrate # sorting of the hash according # alphabetical order of its keysuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting the hash according # alphabetical order of its keysforeach my $name (sort {lc $a cmp lc $b} keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}",
"e": 3061,
"s": 2554,
"text": null
},
{
"code": null,
"e": 3069,
"s": 3061,
"text": "Output:"
},
{
"code": null,
"e": 3186,
"s": 3069,
"text": "Earl 31\nJason 25.2\nMartha 14\nMarty 16.5\nNitin 30\nPlato 39\nSocrates 29.5\nUri 19.6\nVivek 27\n"
},
{
"code": null,
"e": 4437,
"s": 3186,
"text": "Sorting according to the values of Hash: You can also sort the hash according to the values of hash as follows:Example 1: Sorting the hash values according to the ASCII table.# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to ASCII code of values of Hashforeach my $name (sort values %studentnames) { say $name;}Output:14\n16.5\n19.6\n25.2\n27\n29.5\n30\n31\n39\nExample 2: Sorting according to the numerical value of Values of hash as follows:# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to the numerical value of# Values of hashforeach my $name (sort {$a<=>$b} values %studentnames) { say $name;}Output:14\n16.5\n19.6\n25.2\n27\n29.5\n30\n31\n39\n"
},
{
"code": null,
"e": 4502,
"s": 4437,
"text": "Example 1: Sorting the hash values according to the ASCII table."
},
{
"code": "# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to ASCII code of values of Hashforeach my $name (sort values %studentnames) { say $name;}",
"e": 4948,
"s": 4502,
"text": null
},
{
"code": null,
"e": 4956,
"s": 4948,
"text": "Output:"
},
{
"code": null,
"e": 4992,
"s": 4956,
"text": "14\n16.5\n19.6\n25.2\n27\n29.5\n30\n31\n39\n"
},
{
"code": null,
"e": 5074,
"s": 4992,
"text": "Example 2: Sorting according to the numerical value of Values of hash as follows:"
},
{
"code": "# Perl program to demonstrate # sorting of the hash according# to the values of Hashuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 30,Plato => 39,); # sorting of the hash according# to the numerical value of# Values of hashforeach my $name (sort {$a<=>$b} values %studentnames) { say $name;}",
"e": 5540,
"s": 5074,
"text": null
},
{
"code": null,
"e": 5548,
"s": 5540,
"text": "Output:"
},
{
"code": null,
"e": 5584,
"s": 5548,
"text": "14\n16.5\n19.6\n25.2\n27\n29.5\n30\n31\n39\n"
},
{
"code": null,
"e": 7627,
"s": 5584,
"text": "Sort the keys of the hash according to the values: You can also sort the keys of hash according to the given values.Example 1: In the below program, <=> is termed as the spaceship operator. If you will run the code again and again then you can notice the difference in the output. Sometimes you find Plato before the Nitin and vice-versa.# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # Sort the keys of the hash# according to the values# Here $a and $b are the # placeholder variable of sortforeach my $name (sort {$studentnames{$a} <=> $studentnames{$b}} keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}Output:Martha 14\nMarty 16.5\nUri 19.6\nJason 25.2\nVivek 27\nSocrates 29.5\nEarl 31\nPlato 45\nNitin 45\nExample 2: To solve the above code, keys having the same values can be sorted according to the ASCII table as follows:# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # keys that have the same value # will be sorted according the # ASCII tableforeach my $name (sort { $studentnames{$a} <=> $studentnames{$b} or $a cmp $b } keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}Output:Martha 14\nMarty 16.5\nUri 19.6\nJason 25.2\nVivek 27\nSocrates 29.5\nEarl 31\nNitin 45\nPlato 45\nExplanation: Here you can see the key Nitin and Plato are sorted according to the ASCII table. It doesn’t matter how many times you run the code, the output will remain the same."
},
{
"code": null,
"e": 7850,
"s": 7627,
"text": "Example 1: In the below program, <=> is termed as the spaceship operator. If you will run the code again and again then you can notice the difference in the output. Sometimes you find Plato before the Nitin and vice-versa."
},
{
"code": "# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # Sort the keys of the hash# according to the values# Here $a and $b are the # placeholder variable of sortforeach my $name (sort {$studentnames{$a} <=> $studentnames{$b}} keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}",
"e": 8428,
"s": 7850,
"text": null
},
{
"code": null,
"e": 8436,
"s": 8428,
"text": "Output:"
},
{
"code": null,
"e": 8553,
"s": 8436,
"text": "Martha 14\nMarty 16.5\nUri 19.6\nJason 25.2\nVivek 27\nSocrates 29.5\nEarl 31\nPlato 45\nNitin 45\n"
},
{
"code": null,
"e": 8672,
"s": 8553,
"text": "Example 2: To solve the above code, keys having the same values can be sorted according to the ASCII table as follows:"
},
{
"code": "# Perl program to demonstrate the# Sorting of keys of the hash # according to the valuesuse strict;use warnings;use 5.010; # Creating a hash of studentnames # and their average scoremy %studentnames = (Martha => 14,Vivek => 27,Earl => 31,Marty => 16.5,Jason => 25.2,Socrates => 29.5,Uri => 19.6,Nitin => 45,Plato => 45,); # keys that have the same value # will be sorted according the # ASCII tableforeach my $name (sort { $studentnames{$a} <=> $studentnames{$b} or $a cmp $b } keys %studentnames) { printf \"%-8s %s\\n\", $name, $studentnames{$name};}",
"e": 9258,
"s": 8672,
"text": null
},
{
"code": null,
"e": 9266,
"s": 9258,
"text": "Output:"
},
{
"code": null,
"e": 9383,
"s": 9266,
"text": "Martha 14\nMarty 16.5\nUri 19.6\nJason 25.2\nVivek 27\nSocrates 29.5\nEarl 31\nNitin 45\nPlato 45\n"
},
{
"code": null,
"e": 9562,
"s": 9383,
"text": "Explanation: Here you can see the key Nitin and Plato are sorted according to the ASCII table. It doesn’t matter how many times you run the code, the output will remain the same."
},
{
"code": null,
"e": 9574,
"s": 9562,
"text": "Perl-hashes"
},
{
"code": null,
"e": 9579,
"s": 9574,
"text": "Perl"
},
{
"code": null,
"e": 9584,
"s": 9579,
"text": "Perl"
},
{
"code": null,
"e": 9682,
"s": 9584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9723,
"s": 9682,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 9761,
"s": 9723,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 9780,
"s": 9761,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 9814,
"s": 9780,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 9839,
"s": 9814,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 9939,
"s": 9839,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
},
{
"code": null,
"e": 9970,
"s": 9939,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 10004,
"s": 9970,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 10022,
"s": 10004,
"text": "Perl | Data Types"
}
]
|
Object toString() Method in Java | 04 May, 2022
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class, henceforth it is a child of the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes.
Note: Object class acts as a root of inheritance hierarchy in any java program
Now we will be dealing with one of its methods known as toString() method. We typically generally do use the toString() method to get the string representation of an object. It is very important and readers should be aware that whenever we try to print the object reference then internally toString() method is invoked. If we did not define the toString() method in your class then the Object class toString() method is invoked otherwise our implemented or overridden toString() method will be called.
Syntax:
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
Note: Default behavior of toString() is to print class name, then @, then unsigned hexadecimal representation of the hash code of the object.
Example
JAVA
// Java program to Illustrate// working of toString() method // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This variable refers to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method of this class // Main driver method public static void main(String[] args) { // Creating an object of this class // Custom attributes been passed as in arguments Best_Friend b = new Best_Friend( "Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); // Print and display commands to illustrate // toString() method as both will print the same // Print the object System.out.println(b); // Print the object but implicitly using toString() // method System.out.println(b.toString()); }}
Best_Friend@3d075dc0
Best_Friend@3d075dc0
Output explanation: In the above program, we create an Object of Best_Friend class and provide all the information of a friend. But when we try to print the Object, then we are getting some output which is in the form of classname@HashCode_in_Hexadeciaml_form. If we want the proper information about the Best_friend object, then we have to override the toString() method of the Object class in our Best_Friend class.
Example 2:
JAVA
// Java program to illustrate// working of toString() method // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This keyword refers to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method 1 // Creating our own toString() method public String toString() { return name + " " + age + " " + college + " " + course + " " + address; } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of class inside main() method Best_Friend b = new Best_Friend( "Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); // Print and display commands to illustrate // toString() method as both will print the same // Print the object System.out.println(b); // Printing object but using toString() method System.out.println(b.toString()); }}
Gulpreet Kaur 21 BIT MESRA M.TECH Kiriburu
Gulpreet Kaur 21 BIT MESRA M.TECH Kiriburu
Note: In all wrapper classes, all collection classes, String class, StringBuffer, StringBuilder classes toString() method is overridden for meaningful String representation. Hence, it is highly recommended to override toString() method in our class also.
Example 3:
JAVA
// Java program to illustrate// working of toString() method // Importing all utility classesimport java.util.*; // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This keyword refer to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method of this class public static void main(String[] args) { // Creating an object of class in main() method Best_Friend b = new Best_Friend( "Gulpreet Kaur", 21, "BIT MESRA", "M.TECH", "Kiriburu"); System.out.println(b); String s = new String("Gulpreet Kaur"); System.out.println(s); Integer i = new Integer(21); System.out.println(i); ArrayList l = new ArrayList(); l.add("BIT"); l.add("M.TECH"); System.out.println(l); }}
Output: It will also do throw out for warning of unchecked and unsafe operations
Best_Friend@232204a1
Gulpreet Kaur
21
[BIT, M.TECH]
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
gabaa406
anikakapoor
sumitgumber28
surinderdawra388
Java-lang package
Java-Strings
Java
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 436,
"s": 52,
"text": "Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class, henceforth it is a child of the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes."
},
{
"code": null,
"e": 515,
"s": 436,
"text": "Note: Object class acts as a root of inheritance hierarchy in any java program"
},
{
"code": null,
"e": 1017,
"s": 515,
"text": "Now we will be dealing with one of its methods known as toString() method. We typically generally do use the toString() method to get the string representation of an object. It is very important and readers should be aware that whenever we try to print the object reference then internally toString() method is invoked. If we did not define the toString() method in your class then the Object class toString() method is invoked otherwise our implemented or overridden toString() method will be called."
},
{
"code": null,
"e": 1026,
"s": 1017,
"text": "Syntax: "
},
{
"code": null,
"e": 1126,
"s": 1026,
"text": "public String toString() {\n return getClass().getName()+\"@\"+Integer.toHexString(hashCode());\n}"
},
{
"code": null,
"e": 1268,
"s": 1126,
"text": "Note: Default behavior of toString() is to print class name, then @, then unsigned hexadecimal representation of the hash code of the object."
},
{
"code": null,
"e": 1276,
"s": 1268,
"text": "Example"
},
{
"code": null,
"e": 1281,
"s": 1276,
"text": "JAVA"
},
{
"code": "// Java program to Illustrate// working of toString() method // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This variable refers to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method of this class // Main driver method public static void main(String[] args) { // Creating an object of this class // Custom attributes been passed as in arguments Best_Friend b = new Best_Friend( \"Gulpreet Kaur\", 21, \"BIT MESRA\", \"M.TECH\", \"Kiriburu\"); // Print and display commands to illustrate // toString() method as both will print the same // Print the object System.out.println(b); // Print the object but implicitly using toString() // method System.out.println(b.toString()); }}",
"e": 2444,
"s": 1281,
"text": null
},
{
"code": null,
"e": 2486,
"s": 2444,
"text": "Best_Friend@3d075dc0\nBest_Friend@3d075dc0"
},
{
"code": null,
"e": 2904,
"s": 2486,
"text": "Output explanation: In the above program, we create an Object of Best_Friend class and provide all the information of a friend. But when we try to print the Object, then we are getting some output which is in the form of classname@HashCode_in_Hexadeciaml_form. If we want the proper information about the Best_friend object, then we have to override the toString() method of the Object class in our Best_Friend class."
},
{
"code": null,
"e": 2915,
"s": 2904,
"text": "Example 2:"
},
{
"code": null,
"e": 2920,
"s": 2915,
"text": "JAVA"
},
{
"code": "// Java program to illustrate// working of toString() method // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This keyword refers to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method 1 // Creating our own toString() method public String toString() { return name + \" \" + age + \" \" + college + \" \" + course + \" \" + address; } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of class inside main() method Best_Friend b = new Best_Friend( \"Gulpreet Kaur\", 21, \"BIT MESRA\", \"M.TECH\", \"Kiriburu\"); // Print and display commands to illustrate // toString() method as both will print the same // Print the object System.out.println(b); // Printing object but using toString() method System.out.println(b.toString()); }}",
"e": 4190,
"s": 2920,
"text": null
},
{
"code": null,
"e": 4276,
"s": 4190,
"text": "Gulpreet Kaur 21 BIT MESRA M.TECH Kiriburu\nGulpreet Kaur 21 BIT MESRA M.TECH Kiriburu"
},
{
"code": null,
"e": 4531,
"s": 4276,
"text": "Note: In all wrapper classes, all collection classes, String class, StringBuffer, StringBuilder classes toString() method is overridden for meaningful String representation. Hence, it is highly recommended to override toString() method in our class also."
},
{
"code": null,
"e": 4542,
"s": 4531,
"text": "Example 3:"
},
{
"code": null,
"e": 4547,
"s": 4542,
"text": "JAVA"
},
{
"code": "// Java program to illustrate// working of toString() method // Importing all utility classesimport java.util.*; // Main classclass Best_Friend { // Member attributes of this class String name; int age; String college; String course; String address; // Constructor of this class Best_Friend(String name, int age, String college, String course, String address) { // This keyword refer to current instance itself this.name = name; this.age = age; this.college = college; this.course = course; this.address = address; } // Method of this class public static void main(String[] args) { // Creating an object of class in main() method Best_Friend b = new Best_Friend( \"Gulpreet Kaur\", 21, \"BIT MESRA\", \"M.TECH\", \"Kiriburu\"); System.out.println(b); String s = new String(\"Gulpreet Kaur\"); System.out.println(s); Integer i = new Integer(21); System.out.println(i); ArrayList l = new ArrayList(); l.add(\"BIT\"); l.add(\"M.TECH\"); System.out.println(l); }}",
"e": 5701,
"s": 4547,
"text": null
},
{
"code": null,
"e": 5782,
"s": 5701,
"text": "Output: It will also do throw out for warning of unchecked and unsafe operations"
},
{
"code": null,
"e": 5834,
"s": 5782,
"text": "Best_Friend@232204a1\nGulpreet Kaur\n21\n[BIT, M.TECH]"
},
{
"code": null,
"e": 6260,
"s": 5834,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6274,
"s": 6260,
"text": "solankimayank"
},
{
"code": null,
"e": 6283,
"s": 6274,
"text": "gabaa406"
},
{
"code": null,
"e": 6295,
"s": 6283,
"text": "anikakapoor"
},
{
"code": null,
"e": 6309,
"s": 6295,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6326,
"s": 6309,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6344,
"s": 6326,
"text": "Java-lang package"
},
{
"code": null,
"e": 6357,
"s": 6344,
"text": "Java-Strings"
},
{
"code": null,
"e": 6362,
"s": 6357,
"text": "Java"
},
{
"code": null,
"e": 6381,
"s": 6362,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6394,
"s": 6381,
"text": "Java-Strings"
},
{
"code": null,
"e": 6399,
"s": 6394,
"text": "Java"
},
{
"code": null,
"e": 6497,
"s": 6399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6548,
"s": 6497,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6579,
"s": 6548,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6609,
"s": 6579,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6624,
"s": 6609,
"text": "Stream In Java"
},
{
"code": null,
"e": 6642,
"s": 6624,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6662,
"s": 6642,
"text": "Collections in Java"
},
{
"code": null,
"e": 6686,
"s": 6662,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6718,
"s": 6686,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6730,
"s": 6718,
"text": "Set in Java"
}
]
|
std::count() in C++ STL | 22 Sep, 2019
std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val.
// Returns count of occurrences of value in// range [begin, end]int count(Iterator first, Iterator last, T &val)
first, last : Input iterators to the initial and final positions of the sequence of elements.val : Value to match
Complexity It’s order of complexity O(n). Compares once each element with the particular value.
Counting occurrences in an array.
// C++ program for count in C++ STL for// array#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 3, 2, 1, 3, 3, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Number of times 3 appears : " << count(arr, arr + n, 3); return 0;}
Number of times 3 appears : 4
Counting occurrences in a vector.
// C++ program for count in C++ STL for// a vector#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect{ 3, 2, 1, 3, 3, 5, 3 }; cout << "Number of times 3 appears : " << count(vect.begin(), vect.end(), 3); return 0;}
Number of times 3 appears : 4
Counting occurrences in a string.
// C++ program for the count in C++ STL// for a string#include <bits/stdc++.h>using namespace std; int main(){ string str = "geeksforgeeks"; cout << "Number of times 'e' appears : " << count(str.begin(), str.end(), 'e'); return 0;}
Number of times 'e' appears : 4
This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
saurved785
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Sep, 2019"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val."
},
{
"code": null,
"e": 324,
"s": 211,
"text": "// Returns count of occurrences of value in// range [begin, end]int count(Iterator first, Iterator last, T &val)"
},
{
"code": null,
"e": 438,
"s": 324,
"text": "first, last : Input iterators to the initial and final positions of the sequence of elements.val : Value to match"
},
{
"code": null,
"e": 534,
"s": 438,
"text": "Complexity It’s order of complexity O(n). Compares once each element with the particular value."
},
{
"code": null,
"e": 568,
"s": 534,
"text": "Counting occurrences in an array."
},
{
"code": "// C++ program for count in C++ STL for// array#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 3, 2, 1, 3, 3, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Number of times 3 appears : \" << count(arr, arr + n, 3); return 0;}",
"e": 847,
"s": 568,
"text": null
},
{
"code": null,
"e": 878,
"s": 847,
"text": "Number of times 3 appears : 4\n"
},
{
"code": null,
"e": 912,
"s": 878,
"text": "Counting occurrences in a vector."
},
{
"code": "// C++ program for count in C++ STL for// a vector#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect{ 3, 2, 1, 3, 3, 5, 3 }; cout << \"Number of times 3 appears : \" << count(vect.begin(), vect.end(), 3); return 0;}",
"e": 1169,
"s": 912,
"text": null
},
{
"code": null,
"e": 1200,
"s": 1169,
"text": "Number of times 3 appears : 4\n"
},
{
"code": null,
"e": 1234,
"s": 1200,
"text": "Counting occurrences in a string."
},
{
"code": "// C++ program for the count in C++ STL// for a string#include <bits/stdc++.h>using namespace std; int main(){ string str = \"geeksforgeeks\"; cout << \"Number of times 'e' appears : \" << count(str.begin(), str.end(), 'e'); return 0;}",
"e": 1489,
"s": 1234,
"text": null
},
{
"code": null,
"e": 1522,
"s": 1489,
"text": "Number of times 'e' appears : 4\n"
},
{
"code": null,
"e": 1821,
"s": 1522,
"text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1946,
"s": 1821,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1957,
"s": 1946,
"text": "saurved785"
},
{
"code": null,
"e": 1979,
"s": 1957,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 1983,
"s": 1979,
"text": "STL"
},
{
"code": null,
"e": 1987,
"s": 1983,
"text": "C++"
},
{
"code": null,
"e": 1991,
"s": 1987,
"text": "STL"
},
{
"code": null,
"e": 1995,
"s": 1991,
"text": "CPP"
}
]
|
Introduction to Data Structures | 28 Jun, 2022
WHAT IS DATA :
Data is the collection of different numbers, symbols, and alphabets to represent information.
WHAT IS DATA STRUCTURE :
A data structure is a group of data elements that provides the easiest way to store and perform different actions on the data of the computer. A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks.
The choice of a good data structure makes it possible to perform a variety of critical operations effectively. An efficient data structure also uses minimum memory space and execution time to process the structure.
A data structure has also defined an instance of ADT.ADT means ABSTRACT DATA TYPE. It is formally defined as a triplet.[ D,F,A]
D: Set of the domain.
F: the set of operations.
A: the set of axioms.
Type of data structure :
Linear Data Structure Non-Linear Data Structure.
Linear Data Structure
Non-Linear Data Structure.
Linear Data Structure:
Elements are arranged in one dimension ,also known as linear dimension.
Example: lists, stack, queue, etc.
Non-Linear Data Structure
Elements are arranged in one-many, many-one and many-many dimensions.
Example: tree, graph, table, etc.
Data structures are used in various fields such as:
Operating system
Graphics
Computer Design
Blockchain
Genetics
Image Processing
Simulation etc.
Advance your Software Engineering career by learning data structure and algorithms with GeeksforGeek’s most popular DSA course, curated by industry experts to help you get prepared for technical SDE interviews with top-notch companies like Amazon, Microsoft, Adobe and other top product-based giants. Master all the key topics of DSA like sorting, DP, searching, trees and more. Enrol now!
Below is an overview of some popular data structures:
1. Array: An array is a collection of data items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
2. Linked Lists: Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers.
3.Stack: Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all insertion and deletion are permitted at only one end of the list.
Mainly the following three basic operations are performed in the stack:
Initialize: Make a stack empty.
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of the stack.
isEmpty: Returns true if the stack is empty, else false.
4. Queue: Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In the queue, items are inserted at one end and deleted from the other end. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
Mainly the following four basic operations are performed on queue:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition.
Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition.
Front: Get the front item from the queue.
Rear: Get the last item from the queue.
5. Binary Tree: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. It is implemented mainly using Links.
A Binary Tree is represented by a pointer to the topmost node in the tree. If the tree is empty, then the value of root is NULL. A Binary Tree node contains the following parts.
1. Data
2. Pointer to left child
3. Pointer to the right child
6. Binary Search Tree: In Binary Search Tree is a Binary Tree with the following additional properties:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
7. Heap: A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types:
Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree.
Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree.
8. Hashing Data Structure: Hashing is an important Data Structure which is designed to use a special function called the Hash function which is used to map a given value with a particular key for faster access of elements. The efficiency of mapping depends on the efficiency of the hash function used.
Let a hash function H(x) maps the value x at the index x%10 in an Array. For example, if the list of values is [11, 12, 13, 14, 15] it will be stored at positions {1, 2, 3, 4, 5} in the array or Hash table respectively.
9. Matrix: A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets.
A matrix with 9 elements is shown below.
10. Trie: Trie is an efficient information reTrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). If we store keys in the binary search tree, a well-balanced BST will need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements.
itskawal2000
reshmapatil2772
iamsamar12
Arrays
Data Structures
Data Structures
Graph
Heap
Linked List
Queue
Stack
Tree
Data Structures
Linked List
Arrays
Stack
Graph
Queue
Tree
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Types of Linked List
Difference between Stack and Queue Data Structures
What is Competitive Programming and How to Prepare for It?
Data Structures | Array | Question 2
Advantages and Disadvantages of Linked List | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 67,
"s": 52,
"text": "WHAT IS DATA :"
},
{
"code": null,
"e": 161,
"s": 67,
"text": "Data is the collection of different numbers, symbols, and alphabets to represent information."
},
{
"code": null,
"e": 186,
"s": 161,
"text": "WHAT IS DATA STRUCTURE :"
},
{
"code": null,
"e": 510,
"s": 186,
"text": "A data structure is a group of data elements that provides the easiest way to store and perform different actions on the data of the computer. A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. "
},
{
"code": null,
"e": 725,
"s": 510,
"text": "The choice of a good data structure makes it possible to perform a variety of critical operations effectively. An efficient data structure also uses minimum memory space and execution time to process the structure."
},
{
"code": null,
"e": 853,
"s": 725,
"text": "A data structure has also defined an instance of ADT.ADT means ABSTRACT DATA TYPE. It is formally defined as a triplet.[ D,F,A]"
},
{
"code": null,
"e": 875,
"s": 853,
"text": "D: Set of the domain."
},
{
"code": null,
"e": 902,
"s": 875,
"text": "F: the set of operations."
},
{
"code": null,
"e": 925,
"s": 902,
"text": "A: the set of axioms."
},
{
"code": null,
"e": 950,
"s": 925,
"text": "Type of data structure :"
},
{
"code": null,
"e": 1006,
"s": 950,
"text": " Linear Data Structure Non-Linear Data Structure."
},
{
"code": null,
"e": 1032,
"s": 1006,
"text": " Linear Data Structure"
},
{
"code": null,
"e": 1063,
"s": 1032,
"text": " Non-Linear Data Structure."
},
{
"code": null,
"e": 1088,
"s": 1063,
"text": " Linear Data Structure:"
},
{
"code": null,
"e": 1161,
"s": 1088,
"text": " Elements are arranged in one dimension ,also known as linear dimension."
},
{
"code": null,
"e": 1197,
"s": 1161,
"text": " Example: lists, stack, queue, etc."
},
{
"code": null,
"e": 1226,
"s": 1197,
"text": " Non-Linear Data Structure"
},
{
"code": null,
"e": 1298,
"s": 1226,
"text": " Elements are arranged in one-many, many-one and many-many dimensions."
},
{
"code": null,
"e": 1333,
"s": 1298,
"text": " Example: tree, graph, table, etc."
},
{
"code": null,
"e": 1385,
"s": 1333,
"text": "Data structures are used in various fields such as:"
},
{
"code": null,
"e": 1402,
"s": 1385,
"text": "Operating system"
},
{
"code": null,
"e": 1411,
"s": 1402,
"text": "Graphics"
},
{
"code": null,
"e": 1427,
"s": 1411,
"text": "Computer Design"
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": "Blockchain"
},
{
"code": null,
"e": 1447,
"s": 1438,
"text": "Genetics"
},
{
"code": null,
"e": 1464,
"s": 1447,
"text": "Image Processing"
},
{
"code": null,
"e": 1480,
"s": 1464,
"text": "Simulation etc."
},
{
"code": null,
"e": 1870,
"s": 1480,
"text": "Advance your Software Engineering career by learning data structure and algorithms with GeeksforGeek’s most popular DSA course, curated by industry experts to help you get prepared for technical SDE interviews with top-notch companies like Amazon, Microsoft, Adobe and other top product-based giants. Master all the key topics of DSA like sorting, DP, searching, trees and more. Enrol now!"
},
{
"code": null,
"e": 1925,
"s": 1870,
"text": "Below is an overview of some popular data structures: "
},
{
"code": null,
"e": 2290,
"s": 1925,
"text": "1. Array: An array is a collection of data items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). "
},
{
"code": null,
"e": 2482,
"s": 2294,
"text": "2. Linked Lists: Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. "
},
{
"code": null,
"e": 2747,
"s": 2484,
"text": "3.Stack: Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all insertion and deletion are permitted at only one end of the list."
},
{
"code": null,
"e": 2822,
"s": 2749,
"text": "Mainly the following three basic operations are performed in the stack: "
},
{
"code": null,
"e": 2856,
"s": 2824,
"text": "Initialize: Make a stack empty."
},
{
"code": null,
"e": 2956,
"s": 2856,
"text": "Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition."
},
{
"code": null,
"e": 3131,
"s": 2956,
"text": "Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition."
},
{
"code": null,
"e": 3178,
"s": 3131,
"text": "Peek or Top: Returns top element of the stack."
},
{
"code": null,
"e": 3235,
"s": 3178,
"text": "isEmpty: Returns true if the stack is empty, else false."
},
{
"code": null,
"e": 3764,
"s": 3235,
"text": "4. Queue: Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In the queue, items are inserted at one end and deleted from the other end. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. "
},
{
"code": null,
"e": 3834,
"s": 3766,
"text": "Mainly the following four basic operations are performed on queue: "
},
{
"code": null,
"e": 3939,
"s": 3836,
"text": "Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition."
},
{
"code": null,
"e": 4114,
"s": 3939,
"text": "Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition."
},
{
"code": null,
"e": 4156,
"s": 4114,
"text": "Front: Get the front item from the queue."
},
{
"code": null,
"e": 4196,
"s": 4156,
"text": "Rear: Get the last item from the queue."
},
{
"code": null,
"e": 4517,
"s": 4196,
"text": "5. Binary Tree: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. It is implemented mainly using Links. "
},
{
"code": null,
"e": 4697,
"s": 4517,
"text": "A Binary Tree is represented by a pointer to the topmost node in the tree. If the tree is empty, then the value of root is NULL. A Binary Tree node contains the following parts. "
},
{
"code": null,
"e": 4760,
"s": 4697,
"text": "1. Data\n2. Pointer to left child\n3. Pointer to the right child"
},
{
"code": null,
"e": 4867,
"s": 4760,
"text": "6. Binary Search Tree: In Binary Search Tree is a Binary Tree with the following additional properties: "
},
{
"code": null,
"e": 4950,
"s": 4867,
"text": "The left subtree of a node contains only nodes with keys less than the node’s key."
},
{
"code": null,
"e": 5037,
"s": 4950,
"text": "The right subtree of a node contains only nodes with keys greater than the node’s key."
},
{
"code": null,
"e": 5104,
"s": 5037,
"text": "The left and right subtree each must also be a binary search tree."
},
{
"code": null,
"e": 5244,
"s": 5104,
"text": "7. Heap: A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types: "
},
{
"code": null,
"e": 5447,
"s": 5244,
"text": "Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree."
},
{
"code": null,
"e": 5649,
"s": 5447,
"text": "Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree."
},
{
"code": null,
"e": 5952,
"s": 5649,
"text": "8. Hashing Data Structure: Hashing is an important Data Structure which is designed to use a special function called the Hash function which is used to map a given value with a particular key for faster access of elements. The efficiency of mapping depends on the efficiency of the hash function used. "
},
{
"code": null,
"e": 6173,
"s": 5952,
"text": "Let a hash function H(x) maps the value x at the index x%10 in an Array. For example, if the list of values is [11, 12, 13, 14, 15] it will be stored at positions {1, 2, 3, 4, 5} in the array or Hash table respectively. "
},
{
"code": null,
"e": 6355,
"s": 6177,
"text": "9. Matrix: A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. "
},
{
"code": null,
"e": 6398,
"s": 6355,
"text": "A matrix with 9 elements is shown below. "
},
{
"code": null,
"e": 6833,
"s": 6400,
"text": "10. Trie: Trie is an efficient information reTrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). If we store keys in the binary search tree, a well-balanced BST will need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements. "
},
{
"code": null,
"e": 6852,
"s": 6839,
"text": "itskawal2000"
},
{
"code": null,
"e": 6868,
"s": 6852,
"text": "reshmapatil2772"
},
{
"code": null,
"e": 6879,
"s": 6868,
"text": "iamsamar12"
},
{
"code": null,
"e": 6886,
"s": 6879,
"text": "Arrays"
},
{
"code": null,
"e": 6902,
"s": 6886,
"text": "Data Structures"
},
{
"code": null,
"e": 6918,
"s": 6902,
"text": "Data Structures"
},
{
"code": null,
"e": 6924,
"s": 6918,
"text": "Graph"
},
{
"code": null,
"e": 6929,
"s": 6924,
"text": "Heap"
},
{
"code": null,
"e": 6941,
"s": 6929,
"text": "Linked List"
},
{
"code": null,
"e": 6947,
"s": 6941,
"text": "Queue"
},
{
"code": null,
"e": 6953,
"s": 6947,
"text": "Stack"
},
{
"code": null,
"e": 6958,
"s": 6953,
"text": "Tree"
},
{
"code": null,
"e": 6974,
"s": 6958,
"text": "Data Structures"
},
{
"code": null,
"e": 6986,
"s": 6974,
"text": "Linked List"
},
{
"code": null,
"e": 6993,
"s": 6986,
"text": "Arrays"
},
{
"code": null,
"e": 6999,
"s": 6993,
"text": "Stack"
},
{
"code": null,
"e": 7005,
"s": 6999,
"text": "Graph"
},
{
"code": null,
"e": 7011,
"s": 7005,
"text": "Queue"
},
{
"code": null,
"e": 7016,
"s": 7011,
"text": "Tree"
},
{
"code": null,
"e": 7021,
"s": 7016,
"text": "Heap"
},
{
"code": null,
"e": 7119,
"s": 7021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7134,
"s": 7119,
"text": "Arrays in Java"
},
{
"code": null,
"e": 7180,
"s": 7134,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 7248,
"s": 7180,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7292,
"s": 7248,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 7324,
"s": 7292,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 7345,
"s": 7324,
"text": "Types of Linked List"
},
{
"code": null,
"e": 7396,
"s": 7345,
"text": "Difference between Stack and Queue Data Structures"
},
{
"code": null,
"e": 7455,
"s": 7396,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 7492,
"s": 7455,
"text": "Data Structures | Array | Question 2"
}
]
|
Shimmer Effect to Image in Android | 23 Feb, 2021
Shimmer Effect is one of the most popular features that we see in most Android apps. We can get to see this Shimmer Effect while loading the screen in animated form. Using Shimmer Effect in the Android app makes a good User Experience. In this article, we are going to see how to implement the Shimmer Effect in the Android app. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Shimmer Effect is mostly used for loading the screen in an attractive form.
Shimmer Effect gives a good appearance to Images in the Android app.
Using Shimmer Effect in our app gives an Animated view of the image.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency of Shimmer Effect library in build.gradle file
Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.
implementation ‘com.facebook.shimmer:shimmer:0.5.0’
now click on Sync now it will sync your all files in build.gradle().
Step 3: Create a new Shimmer Effect in your 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"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" android:paddingLeft="16dp" android:paddingTop="16dp" android:paddingRight="16dp" android:paddingBottom="16dp" tools:context=".MainActivity"> <!--Shimmer Effect--> <com.facebook.shimmer.ShimmerFrameLayout android:id="@+id/shimmer_view_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <!--Image--> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/ic_baseline_account_balance_24" /> <!--Text given to Image--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="35dp" android:text="Bank" android:textColor="@color/purple_200" android:textSize="24dp" android:textStyle="bold" /> </LinearLayout> </com.facebook.shimmer.ShimmerFrameLayout> <!--Button1 to start Shimmer Effect--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" android:paddingLeft="20dp" android:text="Start" /> <!--Button2 to stop Shimmer Effect--> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:paddingRight="20dp" android:text="Stop" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.facebook.shimmer.ShimmerFrameLayout; public class MainActivity extends AppCompatActivity { // Variables created for buttons and Shimmer Button button1, button2; ShimmerFrameLayout container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = findViewById(R.id.button); button2 = findViewById(R.id.button2); // Button 1 to start Shimmer Effect button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If auto-start is set to false container.startShimmer(); } }); // Button 2 to stop Shimmer Effect button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If auto-start is set to false container.stopShimmer(); } }); // Shimmer effect container = (ShimmerFrameLayout) findViewById(R.id.shimmer_view_container); }}
Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.
Android-Animation
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 522,
"s": 28,
"text": "Shimmer Effect is one of the most popular features that we see in most Android apps. We can get to see this Shimmer Effect while loading the screen in animated form. Using Shimmer Effect in the Android app makes a good User Experience. In this article, we are going to see how to implement the Shimmer Effect in the Android app. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 598,
"s": 522,
"text": "Shimmer Effect is mostly used for loading the screen in an attractive form."
},
{
"code": null,
"e": 667,
"s": 598,
"text": "Shimmer Effect gives a good appearance to Images in the Android app."
},
{
"code": null,
"e": 736,
"s": 667,
"text": "Using Shimmer Effect in our app gives an Animated view of the image."
},
{
"code": null,
"e": 765,
"s": 736,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 927,
"s": 765,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 997,
"s": 927,
"text": "Step 2: Add dependency of Shimmer Effect library in build.gradle file"
},
{
"code": null,
"e": 1134,
"s": 997,
"text": "Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section."
},
{
"code": null,
"e": 1186,
"s": 1134,
"text": "implementation ‘com.facebook.shimmer:shimmer:0.5.0’"
},
{
"code": null,
"e": 1255,
"s": 1186,
"text": "now click on Sync now it will sync your all files in build.gradle()."
},
{
"code": null,
"e": 1322,
"s": 1255,
"text": "Step 3: Create a new Shimmer Effect in your activity_main.xml file"
},
{
"code": null,
"e": 1465,
"s": 1322,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1469,
"s": 1465,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/black\" android:paddingLeft=\"16dp\" android:paddingTop=\"16dp\" android:paddingRight=\"16dp\" android:paddingBottom=\"16dp\" tools:context=\".MainActivity\"> <!--Shimmer Effect--> <com.facebook.shimmer.ShimmerFrameLayout android:id=\"@+id/shimmer_view_container\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"vertical\"> <!--Image--> <ImageView android:layout_width=\"150dp\" android:layout_height=\"150dp\" android:src=\"@drawable/ic_baseline_account_balance_24\" /> <!--Text given to Image--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"35dp\" android:text=\"Bank\" android:textColor=\"@color/purple_200\" android:textSize=\"24dp\" android:textStyle=\"bold\" /> </LinearLayout> </com.facebook.shimmer.ShimmerFrameLayout> <!--Button1 to start Shimmer Effect--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentLeft=\"true\" android:layout_alignParentBottom=\"true\" android:paddingLeft=\"20dp\" android:text=\"Start\" /> <!--Button2 to stop Shimmer Effect--> <Button android:id=\"@+id/button2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:paddingRight=\"20dp\" android:text=\"Stop\" /> </RelativeLayout>",
"e": 3808,
"s": 1469,
"text": null
},
{
"code": null,
"e": 3856,
"s": 3808,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4046,
"s": 3856,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4051,
"s": 4046,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.facebook.shimmer.ShimmerFrameLayout; public class MainActivity extends AppCompatActivity { // Variables created for buttons and Shimmer Button button1, button2; ShimmerFrameLayout container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = findViewById(R.id.button); button2 = findViewById(R.id.button2); // Button 1 to start Shimmer Effect button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If auto-start is set to false container.startShimmer(); } }); // Button 2 to stop Shimmer Effect button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If auto-start is set to false container.stopShimmer(); } }); // Shimmer effect container = (ShimmerFrameLayout) findViewById(R.id.shimmer_view_container); }}",
"e": 5330,
"s": 4051,
"text": null
},
{
"code": null,
"e": 5461,
"s": 5330,
"text": "Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below."
},
{
"code": null,
"e": 5479,
"s": 5461,
"text": "Android-Animation"
},
{
"code": null,
"e": 5503,
"s": 5479,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5511,
"s": 5503,
"text": "Android"
},
{
"code": null,
"e": 5516,
"s": 5511,
"text": "Java"
},
{
"code": null,
"e": 5535,
"s": 5516,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5540,
"s": 5535,
"text": "Java"
},
{
"code": null,
"e": 5548,
"s": 5540,
"text": "Android"
},
{
"code": null,
"e": 5646,
"s": 5548,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5715,
"s": 5646,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5747,
"s": 5715,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5796,
"s": 5747,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5835,
"s": 5796,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5877,
"s": 5835,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5892,
"s": 5877,
"text": "Arrays in Java"
},
{
"code": null,
"e": 5936,
"s": 5892,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 5972,
"s": 5936,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5997,
"s": 5972,
"text": "Reverse a string in Java"
}
]
|
Calculating the completeness score using sklearn in Python | 26 May, 2021
An entirely complete clustering is one where each cluster has information that directs a place toward a similar class cluster. Completeness portrays the closeness of the clustering algorithm to this (completeness_score) perfection.
This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way.
Syntax: sklearn.metrics.completeness_score(labels_true, labels_pred)
Parameters:
labels_true:<int array, shape = [n_samples]>: It accepts the ground truth class labels to be used as a reference.
labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate.
Returns: completeness score between 0.0 and 1.0. 1.0 stands for perfectly completeness labeling.
Switching label_true with label_pred will return the homogeneity_score.
Example 1:
Python3
# Importing the modulesimport pandas as pd from sklearn import datasetsfrom sklearn.cluster import KMeans from sklearn.metrics import completeness_score # Loading the data digits = datasets.load_digits() # Separating the dependent and independent variables Y = digits.targetX = digits.data # Building the clustering model kmeans = KMeans(n_clusters = 2) # Training the clustering model kmeans.fit(X) # Storing the predicted Clustering labels labels = kmeans.predict(X) # Evaluating the performance print(completeness_score(Y, labels))
Output:
0.8471148027985769
Example 2: Perfectly completeness:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 0, 1], [1, 0, 1, 0])print(Cscore)
Output:
1.0
Example 3: Non-perfect labeling that further split classes into more clusters can be perfectly completeness:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 2, 3], [0, 0, 1, 1])print(Cscore)
Output:
0.9999999999999999
Example 4: Include samples from different classes don’t make for completeness labeling:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 0, 0, 0], [0, 1, 2, 3])print(Cscore)
Output:
0.0
sweetyty
ML-Clustering
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 261,
"s": 28,
"text": "An entirely complete clustering is one where each cluster has information that directs a place toward a similar class cluster. Completeness portrays the closeness of the clustering algorithm to this (completeness_score) perfection. "
},
{
"code": null,
"e": 408,
"s": 261,
"text": "This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way."
},
{
"code": null,
"e": 477,
"s": 408,
"text": "Syntax: sklearn.metrics.completeness_score(labels_true, labels_pred)"
},
{
"code": null,
"e": 489,
"s": 477,
"text": "Parameters:"
},
{
"code": null,
"e": 603,
"s": 489,
"text": "labels_true:<int array, shape = [n_samples]>: It accepts the ground truth class labels to be used as a reference."
},
{
"code": null,
"e": 695,
"s": 603,
"text": "labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate."
},
{
"code": null,
"e": 792,
"s": 695,
"text": "Returns: completeness score between 0.0 and 1.0. 1.0 stands for perfectly completeness labeling."
},
{
"code": null,
"e": 864,
"s": 792,
"text": "Switching label_true with label_pred will return the homogeneity_score."
},
{
"code": null,
"e": 875,
"s": 864,
"text": "Example 1:"
},
{
"code": null,
"e": 883,
"s": 875,
"text": "Python3"
},
{
"code": "# Importing the modulesimport pandas as pd from sklearn import datasetsfrom sklearn.cluster import KMeans from sklearn.metrics import completeness_score # Loading the data digits = datasets.load_digits() # Separating the dependent and independent variables Y = digits.targetX = digits.data # Building the clustering model kmeans = KMeans(n_clusters = 2) # Training the clustering model kmeans.fit(X) # Storing the predicted Clustering labels labels = kmeans.predict(X) # Evaluating the performance print(completeness_score(Y, labels))",
"e": 1421,
"s": 883,
"text": null
},
{
"code": null,
"e": 1429,
"s": 1421,
"text": "Output:"
},
{
"code": null,
"e": 1448,
"s": 1429,
"text": "0.8471148027985769"
},
{
"code": null,
"e": 1483,
"s": 1448,
"text": "Example 2: Perfectly completeness:"
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "Python3"
},
{
"code": "# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 0, 1], [1, 0, 1, 0])print(Cscore)",
"e": 1686,
"s": 1491,
"text": null
},
{
"code": null,
"e": 1696,
"s": 1686,
"text": " Output: "
},
{
"code": null,
"e": 1701,
"s": 1696,
"text": "1.0 "
},
{
"code": null,
"e": 1810,
"s": 1701,
"text": "Example 3: Non-perfect labeling that further split classes into more clusters can be perfectly completeness:"
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "Python3"
},
{
"code": "# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 2, 3], [0, 0, 1, 1])print(Cscore)",
"e": 2013,
"s": 1818,
"text": null
},
{
"code": null,
"e": 2021,
"s": 2013,
"text": "Output:"
},
{
"code": null,
"e": 2040,
"s": 2021,
"text": "0.9999999999999999"
},
{
"code": null,
"e": 2128,
"s": 2040,
"text": "Example 4: Include samples from different classes don’t make for completeness labeling:"
},
{
"code": null,
"e": 2136,
"s": 2128,
"text": "Python3"
},
{
"code": "# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 0, 0, 0], [0, 1, 2, 3])print(Cscore)",
"e": 2331,
"s": 2136,
"text": null
},
{
"code": null,
"e": 2339,
"s": 2331,
"text": "Output:"
},
{
"code": null,
"e": 2343,
"s": 2339,
"text": "0.0"
},
{
"code": null,
"e": 2354,
"s": 2345,
"text": "sweetyty"
},
{
"code": null,
"e": 2368,
"s": 2354,
"text": "ML-Clustering"
},
{
"code": null,
"e": 2375,
"s": 2368,
"text": "Python"
},
{
"code": null,
"e": 2473,
"s": 2375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2505,
"s": 2473,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2532,
"s": 2505,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2553,
"s": 2532,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2576,
"s": 2553,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2632,
"s": 2576,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2663,
"s": 2632,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2705,
"s": 2663,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2747,
"s": 2705,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2786,
"s": 2747,
"text": "Python | Get unique values from a list"
}
]
|
numpy.diagflat() in Python | 04 Aug, 2021
numpy.diagflat (a, k = 0): Create a two-dimensional array with the array_like input as a diagonal to the new output array.
Parameters :
a : array_like input data with diagonal elements
strong>k : [int, optional, 0 by default]
Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
Returns :
array with the array_like input as a diagonal to the new output array.
Python
# Python Program illustrating# numpy.diagflat method import numpy as geek print("diagflat use on main diagonal : \n", geek.diagflat([1, 7]), "\n") print("diagflat use on main diagonal : \n", geek.diagflat([1, 7, 6]), "\n") # Diagonal above main diagonalprint("diagflat above main diagonal : \n", geek.diagflat([1, 7, 6], 1), "\n")
Output :
diagflat use on main diagonal :
[[1 0]
[0 7]]
diagflat use on main diagonal :
[[1 0 0]
[0 7 0]
[0 0 6]]
diagflat above main diagonal :
[[0 1 0 0]
[0 0 7 0]
[0 0 0 6]
[0 0 0 0]]
Note : These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gabaa406
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "numpy.diagflat (a, k = 0): Create a two-dimensional array with the array_like input as a diagonal to the new output array."
},
{
"code": null,
"e": 165,
"s": 151,
"text": "Parameters : "
},
{
"code": null,
"e": 343,
"s": 165,
"text": "a : array_like input data with diagonal elements\nstrong>k : [int, optional, 0 by default]\n Diagonal we require; k>0 means diagonal above main diagonal or vice versa."
},
{
"code": null,
"e": 355,
"s": 343,
"text": "Returns : "
},
{
"code": null,
"e": 426,
"s": 355,
"text": "array with the array_like input as a diagonal to the new output array."
},
{
"code": null,
"e": 433,
"s": 426,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.diagflat method import numpy as geek print(\"diagflat use on main diagonal : \\n\", geek.diagflat([1, 7]), \"\\n\") print(\"diagflat use on main diagonal : \\n\", geek.diagflat([1, 7, 6]), \"\\n\") # Diagonal above main diagonalprint(\"diagflat above main diagonal : \\n\", geek.diagflat([1, 7, 6], 1), \"\\n\")",
"e": 764,
"s": 433,
"text": null
},
{
"code": null,
"e": 774,
"s": 764,
"text": "Output : "
},
{
"code": null,
"e": 971,
"s": 774,
"text": "diagflat use on main diagonal : \n [[1 0]\n [0 7]] \n\ndiagflat use on main diagonal : \n [[1 0 0]\n [0 7 0]\n [0 0 6]] \n\ndiagflat above main diagonal : \n [[0 1 0 0]\n [0 0 7 0]\n [0 0 0 6]\n [0 0 0 0]] "
},
{
"code": null,
"e": 1074,
"s": 971,
"text": "Note : These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them."
},
{
"code": null,
"e": 1500,
"s": 1074,
"text": " This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1509,
"s": 1500,
"text": "gabaa406"
},
{
"code": null,
"e": 1536,
"s": 1509,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 1549,
"s": 1536,
"text": "Python-numpy"
},
{
"code": null,
"e": 1556,
"s": 1549,
"text": "Python"
}
]
|
How to Add Custom Toolbar Background in Android? | 23 Feb, 2021
A toolbar is basically a form action bar that contains many interactive items. A toolbar supports a more focused feature than an action bar. The toolbar was added in Android Lollipop (API 21) and is the successor of the ActionBar. The toolbar is a ViewGroup that can be put anyplace in the XML layouts. Toolbar’s looks and behavior could be more efficiently customized than the ActionBar. Toolbars are more flexible than ActionBar. One can simply change its color, size, and position. We can also add labels, logos, navigation icons, and other views to it. In this article, we will see how we can customize the toolbar background using various methods. We will be seeing the following methods:
Solid Color Background
Custom Gradient Background
Image Background
Note: Before adding a custom Toolbar in your app remove the default Actionbar in your android app by following this link.
This is the easiest method to add background to a toolbar. In this method, we use the background attribute to set a solid color. We can either enter the hex code of the color, or we can define a color in the values resource directory. Follow the below steps:
Create a toolbar in the activity_main.xml file.
Add a color value in the colors.xml file with a name.
Add background attribute in the toolbar in activity_main.xml file with the name of the color created in colors.xml file.
Below is the code for the activity_main.xml file:
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Toolbar android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/blue" android:title="GeeksForGeeks" /> </RelativeLayout>
Below is the code for the colors.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#6200EE</color> <color name="blue">#3700B3</color> <color name="colorAccent">#03DAC5</color> </resources>
Gradient colors can be created with the help of two or more colors. XML offers us a cool way of creating our own gradient color that can use as a background in many places. Follow the below steps to create and set a gradient background –
Create an XML file in the drawable folder in resources. (Go to the app > res > drawable > Right-click > New > Drawable Resource File and name the file as background)
Create a shape within the item and then put the gradient tag.
Add the following attributes:angle: This will set the angle at which the two colors will fade.startColor: The first color of the background.endColor: The second color of the background.type: This will set whether the fade will be linear or circular.
angle: This will set the angle at which the two colors will fade.
startColor: The first color of the background.
endColor: The second color of the background.
type: This will set whether the fade will be linear or circular.
Once the background XML is created set it in the background attribute in the activity_main.xml file.
Below is the code for the background.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <gradient android:angle="90" android:startColor="#2EDADA" android:endColor="#22B9D3" android:type="linear"/> </shape> </item></selector>
Below is the code for the activity_main.xml file:
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Toolbar android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/background" android:title="GeeksForGeeks" /> </RelativeLayout>
We can also use images as the background instead of colors. For that again we will be using the background attribute in activity_main.xml. The only thing we need to keep in our mind is that the image’s dimensions should be of the same size as that of the toolbar because the background attribute crops to fit the image in the space. See the below steps:
Add the image to the drawable folder in resources.
Set the image in the drawable attribute of the toolbar in the activity_main.xml file.
Make sure the image and the toolbar have the same dimensions.
Below is the code for the activity_main.xml file:
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Toolbar android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/image"/> </RelativeLayout>
Android-Bars
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 723,
"s": 28,
"text": "A toolbar is basically a form action bar that contains many interactive items. A toolbar supports a more focused feature than an action bar. The toolbar was added in Android Lollipop (API 21) and is the successor of the ActionBar. The toolbar is a ViewGroup that can be put anyplace in the XML layouts. Toolbar’s looks and behavior could be more efficiently customized than the ActionBar. Toolbars are more flexible than ActionBar. One can simply change its color, size, and position. We can also add labels, logos, navigation icons, and other views to it. In this article, we will see how we can customize the toolbar background using various methods. We will be seeing the following methods: "
},
{
"code": null,
"e": 746,
"s": 723,
"text": "Solid Color Background"
},
{
"code": null,
"e": 773,
"s": 746,
"text": "Custom Gradient Background"
},
{
"code": null,
"e": 790,
"s": 773,
"text": "Image Background"
},
{
"code": null,
"e": 913,
"s": 790,
"text": "Note: Before adding a custom Toolbar in your app remove the default Actionbar in your android app by following this link. "
},
{
"code": null,
"e": 1172,
"s": 913,
"text": "This is the easiest method to add background to a toolbar. In this method, we use the background attribute to set a solid color. We can either enter the hex code of the color, or we can define a color in the values resource directory. Follow the below steps:"
},
{
"code": null,
"e": 1220,
"s": 1172,
"text": "Create a toolbar in the activity_main.xml file."
},
{
"code": null,
"e": 1274,
"s": 1220,
"text": "Add a color value in the colors.xml file with a name."
},
{
"code": null,
"e": 1395,
"s": 1274,
"text": "Add background attribute in the toolbar in activity_main.xml file with the name of the color created in colors.xml file."
},
{
"code": null,
"e": 1445,
"s": 1395,
"text": "Below is the code for the activity_main.xml file:"
},
{
"code": null,
"e": 1449,
"s": 1445,
"text": "XML"
},
{
"code": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Toolbar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/blue\" android:title=\"GeeksForGeeks\" /> </RelativeLayout>",
"e": 1891,
"s": 1449,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1891,
"text": "Below is the code for the colors.xml file."
},
{
"code": null,
"e": 1938,
"s": 1934,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#6200EE</color> <color name=\"blue\">#3700B3</color> <color name=\"colorAccent\">#03DAC5</color> </resources>",
"e": 2130,
"s": 1938,
"text": null
},
{
"code": null,
"e": 2369,
"s": 2130,
"text": "Gradient colors can be created with the help of two or more colors. XML offers us a cool way of creating our own gradient color that can use as a background in many places. Follow the below steps to create and set a gradient background – "
},
{
"code": null,
"e": 2535,
"s": 2369,
"text": "Create an XML file in the drawable folder in resources. (Go to the app > res > drawable > Right-click > New > Drawable Resource File and name the file as background)"
},
{
"code": null,
"e": 2597,
"s": 2535,
"text": "Create a shape within the item and then put the gradient tag."
},
{
"code": null,
"e": 2847,
"s": 2597,
"text": "Add the following attributes:angle: This will set the angle at which the two colors will fade.startColor: The first color of the background.endColor: The second color of the background.type: This will set whether the fade will be linear or circular."
},
{
"code": null,
"e": 2913,
"s": 2847,
"text": "angle: This will set the angle at which the two colors will fade."
},
{
"code": null,
"e": 2960,
"s": 2913,
"text": "startColor: The first color of the background."
},
{
"code": null,
"e": 3006,
"s": 2960,
"text": "endColor: The second color of the background."
},
{
"code": null,
"e": 3071,
"s": 3006,
"text": "type: This will set whether the fade will be linear or circular."
},
{
"code": null,
"e": 3172,
"s": 3071,
"text": "Once the background XML is created set it in the background attribute in the activity_main.xml file."
},
{
"code": null,
"e": 3219,
"s": 3172,
"text": "Below is the code for the background.xml file."
},
{
"code": null,
"e": 3223,
"s": 3219,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item> <shape> <gradient android:angle=\"90\" android:startColor=\"#2EDADA\" android:endColor=\"#22B9D3\" android:type=\"linear\"/> </shape> </item></selector>",
"e": 3574,
"s": 3223,
"text": null
},
{
"code": null,
"e": 3624,
"s": 3574,
"text": "Below is the code for the activity_main.xml file:"
},
{
"code": null,
"e": 3628,
"s": 3624,
"text": "XML"
},
{
"code": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Toolbar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@drawable/background\" android:title=\"GeeksForGeeks\" /> </RelativeLayout>",
"e": 4079,
"s": 3628,
"text": null
},
{
"code": null,
"e": 4433,
"s": 4079,
"text": "We can also use images as the background instead of colors. For that again we will be using the background attribute in activity_main.xml. The only thing we need to keep in our mind is that the image’s dimensions should be of the same size as that of the toolbar because the background attribute crops to fit the image in the space. See the below steps:"
},
{
"code": null,
"e": 4484,
"s": 4433,
"text": "Add the image to the drawable folder in resources."
},
{
"code": null,
"e": 4570,
"s": 4484,
"text": "Set the image in the drawable attribute of the toolbar in the activity_main.xml file."
},
{
"code": null,
"e": 4632,
"s": 4570,
"text": "Make sure the image and the toolbar have the same dimensions."
},
{
"code": null,
"e": 4682,
"s": 4632,
"text": "Below is the code for the activity_main.xml file:"
},
{
"code": null,
"e": 4686,
"s": 4682,
"text": "XML"
},
{
"code": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Toolbar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@drawable/image\"/> </RelativeLayout>",
"e": 5094,
"s": 4686,
"text": null
},
{
"code": null,
"e": 5107,
"s": 5094,
"text": "Android-Bars"
},
{
"code": null,
"e": 5115,
"s": 5107,
"text": "Android"
},
{
"code": null,
"e": 5123,
"s": 5115,
"text": "Android"
}
]
|
Image Caption Generator using Deep Learning on Flickr8K dataset | 02 Sep, 2020
Generating a caption for a given image is a challenging problem in the deep learning domain. In this article, we will use different techniques of computer vision and NLP to recognize the context of an image and describe them in a natural language like English. we will build a working model of the image caption generator by using CNN (Convolutional Neural Networks) and LSTM (Long short term memory) units.For training our model I’m using Flickr8K dataset. It consists of 8000 unique images and each image will be mapped to five different sentences which will describe the image.
Step 1: Import the required libraries
# linear algebraimport numpy as np # data processing, CSV file I / O (e.g. pd.read_csv)import pandas as pd import osimport tensorflow as tffrom keras.preprocessing.sequence import pad_sequencesfrom keras.preprocessing.text import Tokenizerfrom keras.models import Modelfrom keras.layers import Flatten, Dense, LSTM, Dropout, Embedding, Activationfrom keras.layers import concatenate, BatchNormalization, Inputfrom keras.layers.merge import addfrom keras.utils import to_categorical, plot_modelfrom keras.applications.inception_v3 import InceptionV3, preprocess_inputimport matplotlib.pyplot as plt # for plotting dataimport cv2
Step 2: Load the descriptionsThe format of our file is image and caption separated by a newline (“\n”) i.e, it consists of the name of the image followed by a space and the description of the image in CSV format. Here we need to map the image to its descriptions by storing them in a dictionary.
def load_description(text): mapping = dict() for line in text.split("\n"): token = line.split("\t") if len(line) < 2: # remove short descriptions continue img_id = token[0].split('.')[0] # name of the image img_des = token[1] # description of the image if img_id not in mapping: mapping[img_id] = list() mapping[img_id].append(img_des) return mapping token_path = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Flickr_TextData / Flickr8k.token.txt'text = open(token_path, 'r', encoding = 'utf-8').read()descriptions = load_description(text)print(descriptions['1000268201_693b08cb0e'])
Output:
['A child in a pink dress is climbing up a set of stairs in an entry way .',
'A girl going into a wooden building .',
'A little girl climbing into a wooden playhouse .',
'A little girl climbing the stairs to her playhouse .',
'A little girl in a pink dress going into a wooden cabin .']
Step 3: Cleaning the textOne of the main steps in NLP is to remove noise so that the machine can detect the patterns easily in the text. Noise will be present in the form of special characters such as hashtags, punctuation and numbers. All of which are difficult for computers to understand if they are present in the text. So we need to remove these for better results. Additionally, you can also remove stop words and perform Stemming and Lemmatization by using NLTK library.
def clean_description(desc): for key, des_list in desc.items(): for i in range(len(des_list)): caption = des_list[i] caption = [ch for ch in caption if ch not in string.punctuation] caption = ''.join(caption) caption = caption.split(' ') caption = [word.lower() for word in caption if len(word)>1 and word.isalpha()] caption = ' '.join(caption) des_list[i] = caption clean_description(descriptions)descriptions['1000268201_693b08cb0e']
Step 4: Generate the Vocabulary
Vocabulary is a set of unique words which are present in our text corpus. When processing raw text for NLP, everything is done around the vocabulary.
def to_vocab(desc): words = set() for key in desc.keys(): for line in desc[key]: words.update(line.split()) return wordsvocab = to_vocab(descriptions)
Step 5: Load the images
Here we need to map the images in the training set to their corresponding descriptions which are present in our descriptions variable. Create a list of names of all training images and then create an empty dictionary and map the images to their descriptions using image name as key and a list of descriptions as its value. while mapping the descriptions add unique words at the beginning and end to identify the start and end of the sentence.
import globimages = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Images/'# Create a list of all image names in the directoryimg = glob.glob(images + '*.jpg') train_path = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Flickr_TextData / Flickr_8k.trainImages.txt'train_images = open(train_path, 'r', encoding = 'utf-8').read().split("\n")train_img = [] # list of all images in training setfor im in img: if(im[len(images):] in train_images): train_img.append(im) # load descriptions of training set in a dictionary. Name of the image will act as eydef load_clean_descriptions(des, dataset): dataset_des = dict() for key, des_list in des.items(): if key+'.jpg' in dataset: if key not in dataset_des: dataset_des[key] = list() for line in des_list: desc = 'startseq ' + line + ' endseq' dataset_des[key].append(desc) return dataset_des train_descriptions = load_clean_descriptions(descriptions, train_images)print(train_descriptions['1000268201_693b08cb0e'])
Output:
['startseq child in pink dress is climbing up set of stairs in an entry way endseq',
'startseq girl going into wooden building endseq',
'startseq little girl climbing into wooden playhouse endseq',
'startseq little girl climbing the stairs to her playhouse endseq',
'startseq little girl in pink dress going into wooden cabin endseq']
Step 6: Extract the feature vector from all images
Now we will give an image as an input to our model but unlike humans, machines cannot understand the image by seeing them. So we need to convert the image into an encoding so that the machine can understand the patterns in it. For this task, I’m using transfer learning i.e, we use a pre-trained model that has been already trained on large datasets and extract the features from these models and use them for our work. Here I’m using the InceptionV3 model which has been trained on Imagenet dataset that had 1000 different classes to classify. We can directly import this model from Keras.applications module.
We need to remove the last classification layer to get the (2048, ) dimensional feature vector from InceptionV3 model.
from keras.preprocessing.image import load_img, img_to_arraydef preprocess_img(img_path): # inception v3 excepts img in 299 * 299 * 3 img = load_img(img_path, target_size = (299, 299)) x = img_to_array(img) # Add one more dimension x = np.expand_dims(x, axis = 0) x = preprocess_input(x) return x def encode(image): image = preprocess_img(image) vec = model.predict(image) vec = np.reshape(vec, (vec.shape[1])) return vec base_model = InceptionV3(weights = 'imagenet')model = Model(base_model.input, base_model.layers[-2].output)# run the encode function on all train images and store the feature vectors in a listencoding_train = {}for img in train_img: encoding_train[img[len(images):]] = encode(img)
Step 7: Tokenizing the vocabulary
In this step, we need to tokenize all the words present in our vocabulary. Alternatively, we can use tokenizer in Keras to do this task.
# list of all training captionsall_train_captions = []for key, val in train_descriptions.items(): for caption in val: all_train_captions.append(caption) # consider only words which occur atleast 10 timesvocabulary = vocabthreshold = 10 # you can change this value according to your needword_counts = {}for cap in all_train_captions: for word in cap.split(' '): word_counts[word] = word_counts.get(word, 0) + 1 vocab = [word for word in word_counts if word_counts[word] >= threshold] # word mapping to integersixtoword = {}wordtoix = {} ix = 1for word in vocab: wordtoix[word] = ix ixtoword[ix] = word ix += 1 # find the maximum length of a description in a datasetmax_length = max(len(des.split()) for des in all_train_captions)max_length
Step 8: Glove vector embeddings
GloVe stands for global vectors for word representation. It is an unsupervised learning algorithm developed by Stanford for generating word embeddings by aggregating global word-word co-occurrence matrix from a corpus. Also, we have 8000 images and each image has 5 captions associated with it. It means we have 30000 examples for training our model. As there are more examples you can also use data generator for feeding input in the form of batches to our model rather than giving all at one time. For simplicity, I’m not using this here.
Also, we are going to use an embedding matrix to store the relations between words in our vocabulary. An embedding matrix is a linear mapping of the original space to a real-valued space where entities will have meaningful relationships.
X1, X2, y = list(), list(), list()for key, des_list in train_descriptions.items(): pic = train_features[key + '.jpg'] for cap in des_list: seq = [wordtoix[word] for word in cap.split(' ') if word in wordtoix] for i in range(1, len(seq)): in_seq, out_seq = seq[:i], seq[i] in_seq = pad_sequences([in_seq], maxlen = max_length)[0] out_seq = to_categorical([out_seq], num_classes = vocab_size)[0] # store X1.append(pic) X2.append(in_seq) y.append(out_seq) X2 = np.array(X2)X1 = np.array(X1)y = np.array(y) # load glove vectors for embedding layerembeddings_index = {}golve_path ='/kaggle / input / glove-global-vectors-for-word-representation / glove.6B.200d.txt'glove = open(golve_path, 'r', encoding = 'utf-8').read()for line in glove.split("\n"): values = line.split(" ") word = values[0] indices = np.asarray(values[1: ], dtype = 'float32') embeddings_index[word] = indices emb_dim = 200emb_matrix = np.zeros((vocab_size, emb_dim))for word, i in wordtoix.items(): emb_vec = embeddings_index.get(word) if emb_vec is not None: emb_matrix[i] = emb_vecemb_matrix.shape
Step 9: Define the modelFor defining the structure of our model, we will be using the Keras Model from Functional API. It has three major steps:
Processing the sequence from the text
Extracting the feature vector from the image
Decoding the output by concatenating the above two layers
# define the modelip1 = Input(shape = (2048, ))fe1 = Dropout(0.2)(ip1)fe2 = Dense(256, activation = 'relu')(fe1)ip2 = Input(shape = (max_length, ))se1 = Embedding(vocab_size, emb_dim, mask_zero = True)(ip2)se2 = Dropout(0.2)(se1)se3 = LSTM(256)(se2)decoder1 = add([fe2, se3])decoder2 = Dense(256, activation = 'relu')(decoder1)outputs = Dense(vocab_size, activation = 'softmax')(decoder2)model = Model(inputs = [ip1, ip2], outputs = outputs)
Output:
Caption Generator deep learning model
Step 10: Training the model
For training our model I’m using Adam’s optimizer and loss function as categorical cross-entropy. I’m training the model for 50 epochs which will be enough for predicting the output. In case you have more computational power (no. of GPU’s) you can train it by decreasing batch size and increasing number of epochs.
model.layers[2].set_weights([emb_matrix])model.layers[2].trainable = Falsemodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam')model.fit([X1, X2], y, epochs = 50, batch_size = 256)# you can increase the number of epochs for better results
Output:
Epoch 1/1
292328/292328 [==============================] - 55s 189us/step - loss: 3.8895
Epoch 1/1
292328/292328 [==============================] - 55s 187us/step - loss: 3.1549
Epoch 1/1
292328/292328 [==============================] - 54s 186us/step - loss: 2.9185
Epoch 1/1
292328/292328 [==============================] - 54s 186us/step - loss: 2.7652
Epoch 1/1
292328/292328 [=================>.........] - ETA: 15s - loss: 2.6496
Step 11: Predicting the output
def greedy_search(pic): start = 'startseq' for i in range(max_length): seq = [wordtoix[word] for word in start.split() if word in wordtoix] seq = pad_sequences([seq], maxlen = max_length) yhat = model.predict([pic, seq]) yhat = np.argmax(yhat) word = ixtoword[yhat] start += ' ' + word if word == 'endseq': break final = start.split() final = final[1:-1] final = ' '.join(final) return final
OUTPUT:
Predicted Output: four girls are sitting on wooden floor
Predicted Output: black dog is running through the grass
Predicted Output: man is skateboarding on ramp
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 633,
"s": 52,
"text": "Generating a caption for a given image is a challenging problem in the deep learning domain. In this article, we will use different techniques of computer vision and NLP to recognize the context of an image and describe them in a natural language like English. we will build a working model of the image caption generator by using CNN (Convolutional Neural Networks) and LSTM (Long short term memory) units.For training our model I’m using Flickr8K dataset. It consists of 8000 unique images and each image will be mapped to five different sentences which will describe the image."
},
{
"code": null,
"e": 671,
"s": 633,
"text": "Step 1: Import the required libraries"
},
{
"code": "# linear algebraimport numpy as np # data processing, CSV file I / O (e.g. pd.read_csv)import pandas as pd import osimport tensorflow as tffrom keras.preprocessing.sequence import pad_sequencesfrom keras.preprocessing.text import Tokenizerfrom keras.models import Modelfrom keras.layers import Flatten, Dense, LSTM, Dropout, Embedding, Activationfrom keras.layers import concatenate, BatchNormalization, Inputfrom keras.layers.merge import addfrom keras.utils import to_categorical, plot_modelfrom keras.applications.inception_v3 import InceptionV3, preprocess_inputimport matplotlib.pyplot as plt # for plotting dataimport cv2",
"e": 1302,
"s": 671,
"text": null
},
{
"code": null,
"e": 1598,
"s": 1302,
"text": "Step 2: Load the descriptionsThe format of our file is image and caption separated by a newline (“\\n”) i.e, it consists of the name of the image followed by a space and the description of the image in CSV format. Here we need to map the image to its descriptions by storing them in a dictionary."
},
{
"code": "def load_description(text): mapping = dict() for line in text.split(\"\\n\"): token = line.split(\"\\t\") if len(line) < 2: # remove short descriptions continue img_id = token[0].split('.')[0] # name of the image img_des = token[1] # description of the image if img_id not in mapping: mapping[img_id] = list() mapping[img_id].append(img_des) return mapping token_path = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Flickr_TextData / Flickr8k.token.txt'text = open(token_path, 'r', encoding = 'utf-8').read()descriptions = load_description(text)print(descriptions['1000268201_693b08cb0e'])",
"e": 2283,
"s": 1598,
"text": null
},
{
"code": null,
"e": 2291,
"s": 2283,
"text": "Output:"
},
{
"code": null,
"e": 2587,
"s": 2291,
"text": "['A child in a pink dress is climbing up a set of stairs in an entry way .', \n\n'A girl going into a wooden building .', \n\n'A little girl climbing into a wooden playhouse .', \n\n'A little girl climbing the stairs to her playhouse .', \n\n'A little girl in a pink dress going into a wooden cabin .']\n"
},
{
"code": null,
"e": 3065,
"s": 2587,
"text": "Step 3: Cleaning the textOne of the main steps in NLP is to remove noise so that the machine can detect the patterns easily in the text. Noise will be present in the form of special characters such as hashtags, punctuation and numbers. All of which are difficult for computers to understand if they are present in the text. So we need to remove these for better results. Additionally, you can also remove stop words and perform Stemming and Lemmatization by using NLTK library."
},
{
"code": "def clean_description(desc): for key, des_list in desc.items(): for i in range(len(des_list)): caption = des_list[i] caption = [ch for ch in caption if ch not in string.punctuation] caption = ''.join(caption) caption = caption.split(' ') caption = [word.lower() for word in caption if len(word)>1 and word.isalpha()] caption = ' '.join(caption) des_list[i] = caption clean_description(descriptions)descriptions['1000268201_693b08cb0e']",
"e": 3589,
"s": 3065,
"text": null
},
{
"code": null,
"e": 3621,
"s": 3589,
"text": "Step 4: Generate the Vocabulary"
},
{
"code": null,
"e": 3771,
"s": 3621,
"text": "Vocabulary is a set of unique words which are present in our text corpus. When processing raw text for NLP, everything is done around the vocabulary."
},
{
"code": "def to_vocab(desc): words = set() for key in desc.keys(): for line in desc[key]: words.update(line.split()) return wordsvocab = to_vocab(descriptions)",
"e": 3949,
"s": 3771,
"text": null
},
{
"code": null,
"e": 3973,
"s": 3949,
"text": "Step 5: Load the images"
},
{
"code": null,
"e": 4416,
"s": 3973,
"text": "Here we need to map the images in the training set to their corresponding descriptions which are present in our descriptions variable. Create a list of names of all training images and then create an empty dictionary and map the images to their descriptions using image name as key and a list of descriptions as its value. while mapping the descriptions add unique words at the beginning and end to identify the start and end of the sentence."
},
{
"code": "import globimages = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Images/'# Create a list of all image names in the directoryimg = glob.glob(images + '*.jpg') train_path = '/kaggle / input / flickr8k / flickr_data / Flickr_Data / Flickr_TextData / Flickr_8k.trainImages.txt'train_images = open(train_path, 'r', encoding = 'utf-8').read().split(\"\\n\")train_img = [] # list of all images in training setfor im in img: if(im[len(images):] in train_images): train_img.append(im) # load descriptions of training set in a dictionary. Name of the image will act as eydef load_clean_descriptions(des, dataset): dataset_des = dict() for key, des_list in des.items(): if key+'.jpg' in dataset: if key not in dataset_des: dataset_des[key] = list() for line in des_list: desc = 'startseq ' + line + ' endseq' dataset_des[key].append(desc) return dataset_des train_descriptions = load_clean_descriptions(descriptions, train_images)print(train_descriptions['1000268201_693b08cb0e'])",
"e": 5501,
"s": 4416,
"text": null
},
{
"code": null,
"e": 5509,
"s": 5501,
"text": "Output:"
},
{
"code": null,
"e": 5853,
"s": 5509,
"text": "['startseq child in pink dress is climbing up set of stairs in an entry way endseq', \n\n'startseq girl going into wooden building endseq', \n\n'startseq little girl climbing into wooden playhouse endseq', \n\n'startseq little girl climbing the stairs to her playhouse endseq', \n\n'startseq little girl in pink dress going into wooden cabin endseq']\n"
},
{
"code": null,
"e": 5904,
"s": 5853,
"text": "Step 6: Extract the feature vector from all images"
},
{
"code": null,
"e": 6515,
"s": 5904,
"text": "Now we will give an image as an input to our model but unlike humans, machines cannot understand the image by seeing them. So we need to convert the image into an encoding so that the machine can understand the patterns in it. For this task, I’m using transfer learning i.e, we use a pre-trained model that has been already trained on large datasets and extract the features from these models and use them for our work. Here I’m using the InceptionV3 model which has been trained on Imagenet dataset that had 1000 different classes to classify. We can directly import this model from Keras.applications module."
},
{
"code": null,
"e": 6634,
"s": 6515,
"text": "We need to remove the last classification layer to get the (2048, ) dimensional feature vector from InceptionV3 model."
},
{
"code": "from keras.preprocessing.image import load_img, img_to_arraydef preprocess_img(img_path): # inception v3 excepts img in 299 * 299 * 3 img = load_img(img_path, target_size = (299, 299)) x = img_to_array(img) # Add one more dimension x = np.expand_dims(x, axis = 0) x = preprocess_input(x) return x def encode(image): image = preprocess_img(image) vec = model.predict(image) vec = np.reshape(vec, (vec.shape[1])) return vec base_model = InceptionV3(weights = 'imagenet')model = Model(base_model.input, base_model.layers[-2].output)# run the encode function on all train images and store the feature vectors in a listencoding_train = {}for img in train_img: encoding_train[img[len(images):]] = encode(img)",
"e": 7375,
"s": 6634,
"text": null
},
{
"code": null,
"e": 7409,
"s": 7375,
"text": "Step 7: Tokenizing the vocabulary"
},
{
"code": null,
"e": 7546,
"s": 7409,
"text": "In this step, we need to tokenize all the words present in our vocabulary. Alternatively, we can use tokenizer in Keras to do this task."
},
{
"code": "# list of all training captionsall_train_captions = []for key, val in train_descriptions.items(): for caption in val: all_train_captions.append(caption) # consider only words which occur atleast 10 timesvocabulary = vocabthreshold = 10 # you can change this value according to your needword_counts = {}for cap in all_train_captions: for word in cap.split(' '): word_counts[word] = word_counts.get(word, 0) + 1 vocab = [word for word in word_counts if word_counts[word] >= threshold] # word mapping to integersixtoword = {}wordtoix = {} ix = 1for word in vocab: wordtoix[word] = ix ixtoword[ix] = word ix += 1 # find the maximum length of a description in a datasetmax_length = max(len(des.split()) for des in all_train_captions)max_length",
"e": 8323,
"s": 7546,
"text": null
},
{
"code": null,
"e": 8355,
"s": 8323,
"text": "Step 8: Glove vector embeddings"
},
{
"code": null,
"e": 8896,
"s": 8355,
"text": "GloVe stands for global vectors for word representation. It is an unsupervised learning algorithm developed by Stanford for generating word embeddings by aggregating global word-word co-occurrence matrix from a corpus. Also, we have 8000 images and each image has 5 captions associated with it. It means we have 30000 examples for training our model. As there are more examples you can also use data generator for feeding input in the form of batches to our model rather than giving all at one time. For simplicity, I’m not using this here."
},
{
"code": null,
"e": 9134,
"s": 8896,
"text": "Also, we are going to use an embedding matrix to store the relations between words in our vocabulary. An embedding matrix is a linear mapping of the original space to a real-valued space where entities will have meaningful relationships."
},
{
"code": "X1, X2, y = list(), list(), list()for key, des_list in train_descriptions.items(): pic = train_features[key + '.jpg'] for cap in des_list: seq = [wordtoix[word] for word in cap.split(' ') if word in wordtoix] for i in range(1, len(seq)): in_seq, out_seq = seq[:i], seq[i] in_seq = pad_sequences([in_seq], maxlen = max_length)[0] out_seq = to_categorical([out_seq], num_classes = vocab_size)[0] # store X1.append(pic) X2.append(in_seq) y.append(out_seq) X2 = np.array(X2)X1 = np.array(X1)y = np.array(y) # load glove vectors for embedding layerembeddings_index = {}golve_path ='/kaggle / input / glove-global-vectors-for-word-representation / glove.6B.200d.txt'glove = open(golve_path, 'r', encoding = 'utf-8').read()for line in glove.split(\"\\n\"): values = line.split(\" \") word = values[0] indices = np.asarray(values[1: ], dtype = 'float32') embeddings_index[word] = indices emb_dim = 200emb_matrix = np.zeros((vocab_size, emb_dim))for word, i in wordtoix.items(): emb_vec = embeddings_index.get(word) if emb_vec is not None: emb_matrix[i] = emb_vecemb_matrix.shape",
"e": 10325,
"s": 9134,
"text": null
},
{
"code": null,
"e": 10470,
"s": 10325,
"text": "Step 9: Define the modelFor defining the structure of our model, we will be using the Keras Model from Functional API. It has three major steps:"
},
{
"code": null,
"e": 10508,
"s": 10470,
"text": "Processing the sequence from the text"
},
{
"code": null,
"e": 10553,
"s": 10508,
"text": "Extracting the feature vector from the image"
},
{
"code": null,
"e": 10611,
"s": 10553,
"text": "Decoding the output by concatenating the above two layers"
},
{
"code": "# define the modelip1 = Input(shape = (2048, ))fe1 = Dropout(0.2)(ip1)fe2 = Dense(256, activation = 'relu')(fe1)ip2 = Input(shape = (max_length, ))se1 = Embedding(vocab_size, emb_dim, mask_zero = True)(ip2)se2 = Dropout(0.2)(se1)se3 = LSTM(256)(se2)decoder1 = add([fe2, se3])decoder2 = Dense(256, activation = 'relu')(decoder1)outputs = Dense(vocab_size, activation = 'softmax')(decoder2)model = Model(inputs = [ip1, ip2], outputs = outputs)",
"e": 11053,
"s": 10611,
"text": null
},
{
"code": null,
"e": 11061,
"s": 11053,
"text": "Output:"
},
{
"code": null,
"e": 11099,
"s": 11061,
"text": "Caption Generator deep learning model"
},
{
"code": null,
"e": 11127,
"s": 11099,
"text": "Step 10: Training the model"
},
{
"code": null,
"e": 11442,
"s": 11127,
"text": "For training our model I’m using Adam’s optimizer and loss function as categorical cross-entropy. I’m training the model for 50 epochs which will be enough for predicting the output. In case you have more computational power (no. of GPU’s) you can train it by decreasing batch size and increasing number of epochs."
},
{
"code": "model.layers[2].set_weights([emb_matrix])model.layers[2].trainable = Falsemodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam')model.fit([X1, X2], y, epochs = 50, batch_size = 256)# you can increase the number of epochs for better results",
"e": 11696,
"s": 11442,
"text": null
},
{
"code": null,
"e": 11704,
"s": 11696,
"text": "Output:"
},
{
"code": null,
"e": 12150,
"s": 11704,
"text": "Epoch 1/1\n\n292328/292328 [==============================] - 55s 189us/step - loss: 3.8895\n\nEpoch 1/1\n\n292328/292328 [==============================] - 55s 187us/step - loss: 3.1549\n\nEpoch 1/1\n\n292328/292328 [==============================] - 54s 186us/step - loss: 2.9185\n\nEpoch 1/1\n\n292328/292328 [==============================] - 54s 186us/step - loss: 2.7652\n\nEpoch 1/1\n\n292328/292328 [=================>.........] - ETA: 15s - loss: 2.6496\n"
},
{
"code": null,
"e": 12181,
"s": 12150,
"text": "Step 11: Predicting the output"
},
{
"code": "def greedy_search(pic): start = 'startseq' for i in range(max_length): seq = [wordtoix[word] for word in start.split() if word in wordtoix] seq = pad_sequences([seq], maxlen = max_length) yhat = model.predict([pic, seq]) yhat = np.argmax(yhat) word = ixtoword[yhat] start += ' ' + word if word == 'endseq': break final = start.split() final = final[1:-1] final = ' '.join(final) return final",
"e": 12651,
"s": 12181,
"text": null
},
{
"code": null,
"e": 12659,
"s": 12651,
"text": "OUTPUT:"
},
{
"code": null,
"e": 12716,
"s": 12659,
"text": "Predicted Output: four girls are sitting on wooden floor"
},
{
"code": null,
"e": 12773,
"s": 12716,
"text": "Predicted Output: black dog is running through the grass"
},
{
"code": null,
"e": 12820,
"s": 12773,
"text": "Predicted Output: man is skateboarding on ramp"
},
{
"code": null,
"e": 12837,
"s": 12820,
"text": "Machine Learning"
},
{
"code": null,
"e": 12844,
"s": 12837,
"text": "Python"
},
{
"code": null,
"e": 12861,
"s": 12844,
"text": "Machine Learning"
}
]
|
Grav - Markdown Syntax | Markdown syntax is defined as writing plain text in an easy to read and easy to write format, which is later converted into HTML code. Symbols like (*) or (`) are used in markdown syntax. These symbols are used to bold, creating headers and organize your content.
To use Markdown syntax, you must create a .md file in your user/pages/02.mypage folder. Enable Markdown Syntax in your \user\config\system.yaml configuration file.
There are many benefits of using Markdown syntax, some of them are as follows.
It is easy to learn and has minimum characters.
It is easy to learn and has minimum characters.
When you use markdown there are very few chances of having errors.
When you use markdown there are very few chances of having errors.
Valid XHTML output.
Valid XHTML output.
Your content and visual display is kept separate so that it does not affect the look of your website.
Your content and visual display is kept separate so that it does not affect the look of your website.
You can use any text editor or markdown application.
You can use any text editor or markdown application.
In the following sections, we will discuss the main elements of HTML that are used in markdown.
Each heading tag is created with # for each heading, i.e., from h1 to h6 the number of # increases as shown.
#my new Heading
##my new Heading
###my new Heading
####my new Heading
#####my new Heading
######my new Heading
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
You can write comments in the following format.
<!—
This is my new comment
-->
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Horizontal rules are used to create a thematic break in between paragraphs. You can create breaks between paragraphs using any of the following methods.
___ − Three underscores
___ − Three underscores
--- − Three dashes
--- − Three dashes
*** − Three asterisks
*** − Three asterisks
Open the md file in a browser as localhost/Grav/mypage; you will receive the following result −
Body copy can be defined as writing text in normal format in markdown syntax, no (p) tag is used
It is a way of writing your plain text in an easy to read and write format,
which later gets converted into HTML code.
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Emphasis are the writing formats in markdown syntax that are used to bold, italicize or strikethrough a portion of text. Let us discuss them below −
A portion of text can be made bold using two (**) signs at either sides.
Example
The newest articles from **Advance Online Publication (AOP)** and the current issue.
In this example, we have to show ‘Advance Online Publication (AOP)’ word as bold.
Open the .md file in a browser as localhost/Grav/mypage, you will receive the following result −
Use “_” (underscores) sign at either sides of the word to italicize the text.
Example
The newest articles from _Advance Online Publication_ (AOP) and the current issues.
In this example, we have to italicize “Advance Online Publication” (AOP) word.
Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −
Use two "~~" (tildes) on either sides of the word to strikethrough the word.
Example
The newest articles from ~~Advance Online Publication~~ (AOP) and the current issues.
In this example, we have to strike “Advance Online Publication” (AOP) word.
Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −
To create a block quote, you must add an > sign before the sentence or the word.
Example
>The newest articles from Advance Online Publication (AOP) and the current issues.
In this example we have used a > sign before the sentence.
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Blockquote can also be used in the following way −
>The newest articles from Advance Online Publication (AOP) and the current issues.
>>> The newest articles from Advance Online Publication (AOP) and the current issues.
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Notices can be used to inform or notify about something important.
There are four types of notices − yellow, red, blue and green.
You must use the >>> sign before a yellow notice type that describes !Info or information.
Example
>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential
mediators of fast neurotransmission throughout the nervous system and are implicated
in many neurological disorders.
Use four >>>> signs before a red notice for a Warning.
Example
>>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential
mediators of fast neurotransmission throughout the nervous system and are implicated
in many neurological disorders.
Use five >>>>> signs for a Blue notice type, this describes a Note.
Example
>>>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential
mediators of fast neurotransmission throughout the nervous system and are implicated
in many neurological disorders.
Use six >>>>>> signs before a Green notice type, this describes a Tip.
Example
>>>>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential
mediators of fast neurotransmission throughout the nervous system and are implicated
in many neurological disorders.
Open the md file in a browser as localhost/Grav/mypage; you will receive the following result −
In this section, we will understand how the unordered and ordered lists work in Grav.
In an unordered list, bullets are used. Use *, - , +. symbols for bullets. Use the symbol with space before any text and the bullet will be displayed.
Example
+ Bullet
+ Bullet
+ Bullet
-Bullet
-Bullet
-Bullet
*Bullet
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Add the numbers before you list something.
Example
1. Coffee
2. Tea
3. Green Tea
Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −
In this section, we will understand how the Inline and block code “fences” work in Grav.
Make inline code using (`) for using codes in markdown.
Example
In the given example, '<section></section>' must be converted into code.
Open the .md file in a browser as localhost/Grav/mypage you will receive the following result −
Use (```) fences if you want to block multiple lines of code.
Example
```
You’re Text Here
```
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
In Grav, tables are created by using pipes and dashes under the header section. Pipes must not be vertically aligned.
| Number | Points |
| ------ | ----------- |
| 1 | Eve Jackson 94 |
| 2 | John Doe 80 |
| 3 | Adam Johnson 67 |
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
To get the table contents at the right, you must add a colon on the right side of the dashes below headings.
| Number | Points |
| ------:| -----------: |
| 1 | Eve Jackson 94 |
| 2 | John Doe 80 |
| 3 | Adam Johnson 67 |
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
In this section, we will understand how links work in Grav.
Links are made with the help of ([]) square brackets and (()) parenthesis. In [] brackets, you must write the content and in () write the domain name.
Example
[Follow the Given link](http://www.google.com)
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
In this section, we will understand how to add a title in .md file.
Example
[Google](https://www.gogle.com/google/ "Visit Google!")
Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −
Images are similar to a link but have an exclamation point at the start of the syntax.
Example
![Nature] (/Grav/images/Grav-images.jpg)
Open the .md file in a browser as localhost/Grav/mypage you will receive the following result − | [
{
"code": null,
"e": 2900,
"s": 2636,
"text": "Markdown syntax is defined as writing plain text in an easy to read and easy to write format, which is later converted into HTML code. Symbols like (*) or (`) are used in markdown syntax. These symbols are used to bold, creating headers and organize your content."
},
{
"code": null,
"e": 3064,
"s": 2900,
"text": "To use Markdown syntax, you must create a .md file in your user/pages/02.mypage folder. Enable Markdown Syntax in your \\user\\config\\system.yaml configuration file."
},
{
"code": null,
"e": 3143,
"s": 3064,
"text": "There are many benefits of using Markdown syntax, some of them are as follows."
},
{
"code": null,
"e": 3191,
"s": 3143,
"text": "It is easy to learn and has minimum characters."
},
{
"code": null,
"e": 3239,
"s": 3191,
"text": "It is easy to learn and has minimum characters."
},
{
"code": null,
"e": 3306,
"s": 3239,
"text": "When you use markdown there are very few chances of having errors."
},
{
"code": null,
"e": 3373,
"s": 3306,
"text": "When you use markdown there are very few chances of having errors."
},
{
"code": null,
"e": 3393,
"s": 3373,
"text": "Valid XHTML output."
},
{
"code": null,
"e": 3413,
"s": 3393,
"text": "Valid XHTML output."
},
{
"code": null,
"e": 3515,
"s": 3413,
"text": "Your content and visual display is kept separate so that it does not affect the look of your website."
},
{
"code": null,
"e": 3617,
"s": 3515,
"text": "Your content and visual display is kept separate so that it does not affect the look of your website."
},
{
"code": null,
"e": 3670,
"s": 3617,
"text": "You can use any text editor or markdown application."
},
{
"code": null,
"e": 3723,
"s": 3670,
"text": "You can use any text editor or markdown application."
},
{
"code": null,
"e": 3819,
"s": 3723,
"text": "In the following sections, we will discuss the main elements of HTML that are used in markdown."
},
{
"code": null,
"e": 3928,
"s": 3819,
"text": "Each heading tag is created with # for each heading, i.e., from h1 to h6 the number of # increases as shown."
},
{
"code": null,
"e": 4046,
"s": 3928,
"text": "\t#my new Heading\n\t##my new Heading\n\t###my new Heading\n\t####my new Heading\n\t#####my new Heading\n\t######my new Heading\n"
},
{
"code": null,
"e": 4143,
"s": 4046,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 4191,
"s": 4143,
"text": "You can write comments in the following format."
},
{
"code": null,
"e": 4226,
"s": 4191,
"text": "<!—\n This is my new comment\n-->\n"
},
{
"code": null,
"e": 4323,
"s": 4226,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 4476,
"s": 4323,
"text": "Horizontal rules are used to create a thematic break in between paragraphs. You can create breaks between paragraphs using any of the following methods."
},
{
"code": null,
"e": 4500,
"s": 4476,
"text": "___ − Three underscores"
},
{
"code": null,
"e": 4524,
"s": 4500,
"text": "___ − Three underscores"
},
{
"code": null,
"e": 4543,
"s": 4524,
"text": "--- − Three dashes"
},
{
"code": null,
"e": 4562,
"s": 4543,
"text": "--- − Three dashes"
},
{
"code": null,
"e": 4584,
"s": 4562,
"text": "*** − Three asterisks"
},
{
"code": null,
"e": 4606,
"s": 4584,
"text": "*** − Three asterisks"
},
{
"code": null,
"e": 4702,
"s": 4606,
"text": "Open the md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 4799,
"s": 4702,
"text": "Body copy can be defined as writing text in normal format in markdown syntax, no (p) tag is used"
},
{
"code": null,
"e": 4920,
"s": 4799,
"text": "It is a way of writing your plain text in an easy to read and write format, \nwhich later gets converted into HTML code.\n"
},
{
"code": null,
"e": 5017,
"s": 4920,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 5166,
"s": 5017,
"text": "Emphasis are the writing formats in markdown syntax that are used to bold, italicize or strikethrough a portion of text. Let us discuss them below −"
},
{
"code": null,
"e": 5239,
"s": 5166,
"text": "A portion of text can be made bold using two (**) signs at either sides."
},
{
"code": null,
"e": 5247,
"s": 5239,
"text": "Example"
},
{
"code": null,
"e": 5333,
"s": 5247,
"text": "The newest articles from **Advance Online Publication (AOP)** and the current issue.\n"
},
{
"code": null,
"e": 5415,
"s": 5333,
"text": "In this example, we have to show ‘Advance Online Publication (AOP)’ word as bold."
},
{
"code": null,
"e": 5512,
"s": 5415,
"text": "Open the .md file in a browser as localhost/Grav/mypage, you will receive the following result −"
},
{
"code": null,
"e": 5590,
"s": 5512,
"text": "Use “_” (underscores) sign at either sides of the word to italicize the text."
},
{
"code": null,
"e": 5598,
"s": 5590,
"text": "Example"
},
{
"code": null,
"e": 5683,
"s": 5598,
"text": "The newest articles from _Advance Online Publication_ (AOP) and the current issues.\n"
},
{
"code": null,
"e": 5762,
"s": 5683,
"text": "In this example, we have to italicize “Advance Online Publication” (AOP) word."
},
{
"code": null,
"e": 5861,
"s": 5762,
"text": "Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −"
},
{
"code": null,
"e": 5938,
"s": 5861,
"text": "Use two \"~~\" (tildes) on either sides of the word to strikethrough the word."
},
{
"code": null,
"e": 5946,
"s": 5938,
"text": "Example"
},
{
"code": null,
"e": 6033,
"s": 5946,
"text": "The newest articles from ~~Advance Online Publication~~ (AOP) and the current issues.\n"
},
{
"code": null,
"e": 6109,
"s": 6033,
"text": "In this example, we have to strike “Advance Online Publication” (AOP) word."
},
{
"code": null,
"e": 6208,
"s": 6109,
"text": "Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −"
},
{
"code": null,
"e": 6289,
"s": 6208,
"text": "To create a block quote, you must add an > sign before the sentence or the word."
},
{
"code": null,
"e": 6297,
"s": 6289,
"text": "Example"
},
{
"code": null,
"e": 6381,
"s": 6297,
"text": ">The newest articles from Advance Online Publication (AOP) and the current issues.\n"
},
{
"code": null,
"e": 6440,
"s": 6381,
"text": "In this example we have used a > sign before the sentence."
},
{
"code": null,
"e": 6537,
"s": 6440,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 6588,
"s": 6537,
"text": "Blockquote can also be used in the following way −"
},
{
"code": null,
"e": 6758,
"s": 6588,
"text": ">The newest articles from Advance Online Publication (AOP) and the current issues.\n>>> The newest articles from Advance Online Publication (AOP) and the current issues.\n"
},
{
"code": null,
"e": 6855,
"s": 6758,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 6922,
"s": 6855,
"text": "Notices can be used to inform or notify about something important."
},
{
"code": null,
"e": 6985,
"s": 6922,
"text": "There are four types of notices − yellow, red, blue and green."
},
{
"code": null,
"e": 7076,
"s": 6985,
"text": "You must use the >>> sign before a yellow notice type that describes !Info or information."
},
{
"code": null,
"e": 7084,
"s": 7076,
"text": "Example"
},
{
"code": null,
"e": 7287,
"s": 7084,
"text": ">>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential\nmediators of fast neurotransmission throughout the nervous system and are implicated\nin many neurological disorders.\n"
},
{
"code": null,
"e": 7342,
"s": 7287,
"text": "Use four >>>> signs before a red notice for a Warning."
},
{
"code": null,
"e": 7350,
"s": 7342,
"text": "Example"
},
{
"code": null,
"e": 7554,
"s": 7350,
"text": ">>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential\nmediators of fast neurotransmission throughout the nervous system and are implicated\nin many neurological disorders.\n"
},
{
"code": null,
"e": 7622,
"s": 7554,
"text": "Use five >>>>> signs for a Blue notice type, this describes a Note."
},
{
"code": null,
"e": 7630,
"s": 7622,
"text": "Example"
},
{
"code": null,
"e": 7835,
"s": 7630,
"text": ">>>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential\nmediators of fast neurotransmission throughout the nervous system and are implicated\nin many neurological disorders.\n"
},
{
"code": null,
"e": 7906,
"s": 7835,
"text": "Use six >>>>>> signs before a Green notice type, this describes a Tip."
},
{
"code": null,
"e": 7914,
"s": 7906,
"text": "Example"
},
{
"code": null,
"e": 8120,
"s": 7914,
"text": ">>>>>>Neurotransmitter-gated ion channels of the Cys-loop receptor family are essential\nmediators of fast neurotransmission throughout the nervous system and are implicated\nin many neurological disorders.\n"
},
{
"code": null,
"e": 8216,
"s": 8120,
"text": "Open the md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 8302,
"s": 8216,
"text": "In this section, we will understand how the unordered and ordered lists work in Grav."
},
{
"code": null,
"e": 8453,
"s": 8302,
"text": "In an unordered list, bullets are used. Use *, - , +. symbols for bullets. Use the symbol with space before any text and the bullet will be displayed."
},
{
"code": null,
"e": 8461,
"s": 8453,
"text": "Example"
},
{
"code": null,
"e": 8532,
"s": 8461,
"text": "+ Bullet\n+ Bullet\n+ Bullet\n -Bullet\n -Bullet\n -Bullet\n *Bullet"
},
{
"code": null,
"e": 8629,
"s": 8532,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 8672,
"s": 8629,
"text": "Add the numbers before you list something."
},
{
"code": null,
"e": 8680,
"s": 8672,
"text": "Example"
},
{
"code": null,
"e": 8711,
"s": 8680,
"text": "1. Coffee\n2. Tea\n3. Green Tea\n"
},
{
"code": null,
"e": 8810,
"s": 8711,
"text": "Open the .md file in a browser as localhost/Grav/mypage. This will give you the following result −"
},
{
"code": null,
"e": 8899,
"s": 8810,
"text": "In this section, we will understand how the Inline and block code “fences” work in Grav."
},
{
"code": null,
"e": 8955,
"s": 8899,
"text": "Make inline code using (`) for using codes in markdown."
},
{
"code": null,
"e": 8963,
"s": 8955,
"text": "Example"
},
{
"code": null,
"e": 9037,
"s": 8963,
"text": "In the given example, '<section></section>' must be converted into code.\n"
},
{
"code": null,
"e": 9133,
"s": 9037,
"text": "Open the .md file in a browser as localhost/Grav/mypage you will receive the following result −"
},
{
"code": null,
"e": 9195,
"s": 9133,
"text": "Use (```) fences if you want to block multiple lines of code."
},
{
"code": null,
"e": 9203,
"s": 9195,
"text": "Example"
},
{
"code": null,
"e": 9230,
"s": 9203,
"text": "```\nYou’re Text Here\n\n```\n"
},
{
"code": null,
"e": 9327,
"s": 9230,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 9445,
"s": 9327,
"text": "In Grav, tables are created by using pipes and dashes under the header section. Pipes must not be vertically aligned."
},
{
"code": null,
"e": 9596,
"s": 9445,
"text": "| Number | Points |\n| ------ | ----------- |\n| 1 | Eve Jackson 94 |\n| 2 | John Doe 80 |\n| 3 | Adam Johnson 67 |\n"
},
{
"code": null,
"e": 9693,
"s": 9596,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 9802,
"s": 9693,
"text": "To get the table contents at the right, you must add a colon on the right side of the dashes below headings."
},
{
"code": null,
"e": 9948,
"s": 9802,
"text": "| Number | Points |\n| ------:| -----------: |\n| 1 | Eve Jackson 94 |\n| 2 | John Doe 80 |\n| 3 | Adam Johnson 67 |\n"
},
{
"code": null,
"e": 10045,
"s": 9948,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 10105,
"s": 10045,
"text": "In this section, we will understand how links work in Grav."
},
{
"code": null,
"e": 10256,
"s": 10105,
"text": "Links are made with the help of ([]) square brackets and (()) parenthesis. In [] brackets, you must write the content and in () write the domain name."
},
{
"code": null,
"e": 10264,
"s": 10256,
"text": "Example"
},
{
"code": null,
"e": 10312,
"s": 10264,
"text": "[Follow the Given link](http://www.google.com)\n"
},
{
"code": null,
"e": 10409,
"s": 10312,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 10477,
"s": 10409,
"text": "In this section, we will understand how to add a title in .md file."
},
{
"code": null,
"e": 10485,
"s": 10477,
"text": "Example"
},
{
"code": null,
"e": 10542,
"s": 10485,
"text": "[Google](https://www.gogle.com/google/ \"Visit Google!\")\n"
},
{
"code": null,
"e": 10639,
"s": 10542,
"text": "Open the .md file in a browser as localhost/Grav/mypage; you will receive the following result −"
},
{
"code": null,
"e": 10726,
"s": 10639,
"text": "Images are similar to a link but have an exclamation point at the start of the syntax."
},
{
"code": null,
"e": 10734,
"s": 10726,
"text": "Example"
},
{
"code": null,
"e": 10776,
"s": 10734,
"text": "![Nature] (/Grav/images/Grav-images.jpg)\n"
}
]
|
Convert list of Celsius values into Fahrenheit using NumPy array | 25 Jan, 2022
Let us see how to convert a list of Celsius temperatures into Fahrenheit by converting them into NumPy array. The formula to convert Celsius to Fahrenheit is :
feh = (9 * cel / 5 + 32)
Method 1 : Using the numpy.array() method.
python3
# importing the moduleimport numpy as np # taking the celsius inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.array(inp) print(f"Celsius {cel}") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0. 12. 45.21 34. 99.91]
Fahrenheit [ 32. 53.6 113.378 93.2 211.838]
Method 2 : Using the numpy.asarray() method.
python3
# importing the moduleimport numpy as np # taking the celsius inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.asarray(inp) print(f"Celsius {cel}") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0. 12. 45.21 34. 99.91]
Fahrenheit [ 32. 53.6 113.378 93.2 211.838]
Method 3 : Using numpy.arange().
python3
# importing the moduleimport numpy as np # taking thecelsius inputinp = [0, 12, 45.21, 34, 99.91] # arange will not directly# convert into numpy arraycel = np.arange(5) # the above code# will give o/p as# cel = [0, 1, 2, 3, 4]cel = [i for i in inp]# thus the input(inp)# is stored in cel# using list comprehension print(f"Celsius {cel}") # applying formulae# using list comprehensionfeh = [(9 * i / 5 + 32) for i in cel] # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0. 12. 45.21 34. 99.91]
Fahrenheit [ 32. 53.6 113.378 93.2 211.838]
clintra
Python numpy-program
Python-numpy
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": 28,
"s": 0,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "Let us see how to convert a list of Celsius temperatures into Fahrenheit by converting them into NumPy array. The formula to convert Celsius to Fahrenheit is : "
},
{
"code": null,
"e": 215,
"s": 190,
"text": "feh = (9 * cel / 5 + 32)"
},
{
"code": null,
"e": 260,
"s": 217,
"text": "Method 1 : Using the numpy.array() method."
},
{
"code": null,
"e": 270,
"s": 262,
"text": "python3"
},
{
"code": "# importing the moduleimport numpy as np # taking the celsius inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.array(inp) print(f\"Celsius {cel}\") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f\"Fahrenheit {feh}\")",
"e": 535,
"s": 270,
"text": null
},
{
"code": null,
"e": 544,
"s": 535,
"text": "Output :"
},
{
"code": null,
"e": 637,
"s": 544,
"text": "Celsius [ 0. 12. 45.21 34. 99.91]\nFahrenheit [ 32. 53.6 113.378 93.2 211.838]"
},
{
"code": null,
"e": 682,
"s": 637,
"text": "Method 2 : Using the numpy.asarray() method."
},
{
"code": null,
"e": 690,
"s": 682,
"text": "python3"
},
{
"code": "# importing the moduleimport numpy as np # taking the celsius inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.asarray(inp) print(f\"Celsius {cel}\") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f\"Fahrenheit {feh}\")",
"e": 957,
"s": 690,
"text": null
},
{
"code": null,
"e": 966,
"s": 957,
"text": "Output :"
},
{
"code": null,
"e": 1059,
"s": 966,
"text": "Celsius [ 0. 12. 45.21 34. 99.91]\nFahrenheit [ 32. 53.6 113.378 93.2 211.838]"
},
{
"code": null,
"e": 1092,
"s": 1059,
"text": "Method 3 : Using numpy.arange()."
},
{
"code": null,
"e": 1100,
"s": 1092,
"text": "python3"
},
{
"code": "# importing the moduleimport numpy as np # taking thecelsius inputinp = [0, 12, 45.21, 34, 99.91] # arange will not directly# convert into numpy arraycel = np.arange(5) # the above code# will give o/p as# cel = [0, 1, 2, 3, 4]cel = [i for i in inp]# thus the input(inp)# is stored in cel# using list comprehension print(f\"Celsius {cel}\") # applying formulae# using list comprehensionfeh = [(9 * i / 5 + 32) for i in cel] # printing resultsprint(f\"Fahrenheit {feh}\")",
"e": 1567,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1576,
"s": 1567,
"text": "Output :"
},
{
"code": null,
"e": 1669,
"s": 1576,
"text": "Celsius [ 0. 12. 45.21 34. 99.91]\nFahrenheit [ 32. 53.6 113.378 93.2 211.838]"
},
{
"code": null,
"e": 1677,
"s": 1669,
"text": "clintra"
},
{
"code": null,
"e": 1698,
"s": 1677,
"text": "Python numpy-program"
},
{
"code": null,
"e": 1711,
"s": 1698,
"text": "Python-numpy"
},
{
"code": null,
"e": 1718,
"s": 1711,
"text": "Python"
},
{
"code": null,
"e": 1816,
"s": 1718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1834,
"s": 1816,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1876,
"s": 1834,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1898,
"s": 1876,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1933,
"s": 1898,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1959,
"s": 1933,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1991,
"s": 1959,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2020,
"s": 1991,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2050,
"s": 2020,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2077,
"s": 2050,
"text": "Python Classes and Objects"
}
]
|
jQuery | wrap() with Examples | 13 Feb, 2019
The wrap() method is an inbuilt method in jQuery which is used to wrap the specified element around the selected element.
Syntax:
$(selector).wrap(element, function)
Parameters: This method accepts two parameters as mentioned above and described below:
element: It is required parameter which is used to specify the element to wrap around the selected elements.
function: It is optional parameter which is used to specify the function which returns the wrapping element.
Return Value: This method returns the selected element with the specified changes made by wrap() method.
Below examples illustrate the wrap() method in jQuery:
Example 1: This example does not accept optional parameter.
<!DOCTYPE html><html> <head> <title>The wrap() Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("p").wrap("<div></div>"); }); }); </script> <style> div { background-color: lightgreen; padding: 20px; width: 200px; font-weight: bold; height: 60px; border: 2px solid green; } </style> </head> <body> <!-- click on this paragraph and see the change --> <p>Welcome to GeeksforGeeks!</p><br> <button>Click Here!</button> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title>The wrap Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("p").wrap(function() { return "<div></div>" }); }); }); </script> <style> div { background-color: lightgreen; padding: 20px; width: 200px; font-weight: bold; height: 60px; border: 2px solid green; } </style> </head> <body> <!-- click on this paragraph and see the change --> <p>Welcome to GeeksforGeeks!</p><br> <button>Click Here!</button> </body></html>
Output:
jQuery-HTML/CSS
JavaScript
JQuery
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
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "The wrap() method is an inbuilt method in jQuery which is used to wrap the specified element around the selected element."
},
{
"code": null,
"e": 158,
"s": 150,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 158,
"text": "$(selector).wrap(element, function)"
},
{
"code": null,
"e": 281,
"s": 194,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 390,
"s": 281,
"text": "element: It is required parameter which is used to specify the element to wrap around the selected elements."
},
{
"code": null,
"e": 499,
"s": 390,
"text": "function: It is optional parameter which is used to specify the function which returns the wrapping element."
},
{
"code": null,
"e": 604,
"s": 499,
"text": "Return Value: This method returns the selected element with the specified changes made by wrap() method."
},
{
"code": null,
"e": 659,
"s": 604,
"text": "Below examples illustrate the wrap() method in jQuery:"
},
{
"code": null,
"e": 719,
"s": 659,
"text": "Example 1: This example does not accept optional parameter."
},
{
"code": "<!DOCTYPE html><html> <head> <title>The wrap() Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").wrap(\"<div></div>\"); }); }); </script> <style> div { background-color: lightgreen; padding: 20px; width: 200px; font-weight: bold; height: 60px; border: 2px solid green; } </style> </head> <body> <!-- click on this paragraph and see the change --> <p>Welcome to GeeksforGeeks!</p><br> <button>Click Here!</button> </body></html>",
"e": 1631,
"s": 719,
"text": null
},
{
"code": null,
"e": 1639,
"s": 1631,
"text": "Output:"
},
{
"code": null,
"e": 1650,
"s": 1639,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The wrap Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").wrap(function() { return \"<div></div>\" }); }); }); </script> <style> div { background-color: lightgreen; padding: 20px; width: 200px; font-weight: bold; height: 60px; border: 2px solid green; } </style> </head> <body> <!-- click on this paragraph and see the change --> <p>Welcome to GeeksforGeeks!</p><br> <button>Click Here!</button> </body></html>",
"e": 2617,
"s": 1650,
"text": null
},
{
"code": null,
"e": 2625,
"s": 2617,
"text": "Output:"
},
{
"code": null,
"e": 2641,
"s": 2625,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 2652,
"s": 2641,
"text": "JavaScript"
},
{
"code": null,
"e": 2659,
"s": 2652,
"text": "JQuery"
},
{
"code": null,
"e": 2757,
"s": 2659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2818,
"s": 2757,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2890,
"s": 2818,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2930,
"s": 2890,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2982,
"s": 2930,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3023,
"s": 2982,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3069,
"s": 3023,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 3098,
"s": 3069,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3161,
"s": 3098,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 3214,
"s": 3161,
"text": "How to add options to a select element using jQuery?"
}
]
|
Find the k most frequent words from a file | 11 Jan, 2022
Given a book of words. Assume you have enough main memory to accommodate all words. design a data structure to find top K maximum occurring words. The data structure should be dynamic so that new words can be added. A simple solution is to use Hashing. Hash all words one by one in a hash table. If a word is already present, then increment its count. Finally, traverse through the hash table and return the k words with maximum counts.We can use Trie and Min Heap to get the k most frequent words efficiently. The idea is to use Trie for searching existing words adding new words efficiently. Trie also stores count of occurrences of words. A Min Heap of size k is used to keep track of k most frequent words at any point of time(Use of Min Heap is same as we used it to find k largest elements in this post). Trie and Min Heap are linked with each other by storing an additional field in Trie ‘indexMinHeap’ and a pointer ‘trNode’ in Min Heap. The value of ‘indexMinHeap’ is maintained as -1 for the words which are currently not in Min Heap (or currently not among the top k frequent words). For the words which are present in Min Heap, ‘indexMinHeap’ contains, index of the word in Min Heap. The pointer ‘trNode’ in Min Heap points to the leaf node corresponding to the word in Trie.Following is the complete process to print k most frequent words from a file.Read all words one by one. For every word, insert it into Trie. Increase the counter of the word, if already exists. Now, we need to insert this word in min heap also. For insertion in min heap, 3 cases arise:1. The word is already present. We just increase the corresponding frequency value in min heap and call minHeapify() for the index obtained by “indexMinHeap” field in Trie. When the min heap nodes are being swapped, we change the corresponding minHeapIndex in the Trie. Remember each node of the min heap is also having pointer to Trie leaf node.2. The minHeap is not full. we will insert the new word into min heap & update the root node in the min heap node & min heap index in Trie leaf node. Now, call buildMinHeap().3. The min heap is full. Two sub-cases arise. ....3.1 The frequency of the new word inserted is less than the frequency of the word stored in the head of min heap. Do nothing.....3.2 The frequency of the new word inserted is greater than the frequency of the word stored in the head of min heap. Replace & update the fields. Make sure to update the corresponding min heap index of the “word to be replaced” in Trie with -1 as the word is no longer in min heap.4. Finally, Min Heap will have the k most frequent words of all words present in given file. So we just need to print all words present in Min Heap.
CPP
// A program to find k most frequent words in a file#include <stdio.h>#include <string.h>#include <ctype.h> # define MAX_CHARS 26# define MAX_WORD_SIZE 30 // A Trie nodestruct TrieNode{ bool isEnd; // indicates end of word unsigned frequency; // the number of occurrences of a word int indexMinHeap; // the index of the word in minHeap TrieNode* child[MAX_CHARS]; // represents 26 slots each for 'a' to 'z'.}; // A Min Heap nodestruct MinHeapNode{ TrieNode* root; // indicates the leaf node of TRIE unsigned frequency; // number of occurrences char* word; // the actual word stored}; // A Min Heapstruct MinHeap{ unsigned capacity; // the total size a min heap int count; // indicates the number of slots filled. MinHeapNode* array; // represents the collection of minHeapNodes}; // A utility function to create a new Trie nodeTrieNode* newTrieNode(){ // Allocate memory for Trie Node TrieNode* trieNode = new TrieNode; // Initialize values for new node trieNode->isEnd = 0; trieNode->frequency = 0; trieNode->indexMinHeap = -1; for( int i = 0; i < MAX_CHARS; ++i ) trieNode->child[i] = NULL; return trieNode;} // A utility function to create a Min Heap of given capacityMinHeap* createMinHeap( int capacity ){ MinHeap* minHeap = new MinHeap; minHeap->capacity = capacity; minHeap->count = 0; // Allocate memory for array of min heap nodes minHeap->array = new MinHeapNode [ minHeap->capacity ]; return minHeap;} // A utility function to swap two min heap nodes. This function// is needed in minHeapifyvoid swapMinHeapNodes ( MinHeapNode* a, MinHeapNode* b ){ MinHeapNode temp = *a; *a = *b; *b = temp;} // This is the standard minHeapify function. It does one thing extra.// It updates the minHapIndex in Trie when two nodes are swapped in// in min heapvoid minHeapify( MinHeap* minHeap, int idx ){ int left, right, smallest; left = 2 * idx + 1; right = 2 * idx + 2; smallest = idx; if ( left < minHeap->count && minHeap->array[ left ]. frequency < minHeap->array[ smallest ]. frequency ) smallest = left; if ( right < minHeap->count && minHeap->array[ right ]. frequency < minHeap->array[ smallest ]. frequency ) smallest = right; if( smallest != idx ) { // Update the corresponding index in Trie node. minHeap->array[ smallest ]. root->indexMinHeap = idx; minHeap->array[ idx ]. root->indexMinHeap = smallest; // Swap nodes in min heap swapMinHeapNodes (&minHeap->array[ smallest ], &minHeap->array[ idx ]); minHeapify( minHeap, smallest ); }} // A standard function to build a heapvoid buildMinHeap( MinHeap* minHeap ){ int n, i; n = minHeap->count - 1; for( i = ( n - 1 ) / 2; i >= 0; --i ) minHeapify( minHeap, i );} // Inserts a word to heap, the function handles the 3 cases explained abovevoid insertInMinHeap( MinHeap* minHeap, TrieNode** root, const char* word ){ // Case 1: the word is already present in minHeap if( (*root)->indexMinHeap != -1 ) { ++( minHeap->array[ (*root)->indexMinHeap ]. frequency ); // percolate down minHeapify( minHeap, (*root)->indexMinHeap ); } // Case 2: Word is not present and heap is not full else if( minHeap->count < minHeap->capacity ) { int count = minHeap->count; minHeap->array[ count ]. frequency = (*root)->frequency; minHeap->array[ count ]. word = new char [strlen( word ) + 1]; strcpy( minHeap->array[ count ]. word, word ); minHeap->array[ count ]. root = *root; (*root)->indexMinHeap = minHeap->count; ++( minHeap->count ); buildMinHeap( minHeap ); } // Case 3: Word is not present and heap is full. And frequency of word // is more than root. The root is the least frequent word in heap, // replace root with new word else if ( (*root)->frequency > minHeap->array[0]. frequency ) { minHeap->array[ 0 ]. root->indexMinHeap = -1; minHeap->array[ 0 ]. root = *root; minHeap->array[ 0 ]. root->indexMinHeap = 0; minHeap->array[ 0 ]. frequency = (*root)->frequency; // delete previously allocated memory and delete [] minHeap->array[ 0 ]. word; minHeap->array[ 0 ]. word = new char [strlen( word ) + 1]; strcpy( minHeap->array[ 0 ]. word, word ); minHeapify ( minHeap, 0 ); }} // Inserts a new word to both Trie and Heapvoid insertUtil ( TrieNode** root, MinHeap* minHeap, const char* word, const char* dupWord ){ // Base Case if ( *root == NULL ) *root = newTrieNode(); // There are still more characters in word if ( *word != '\0' ) insertUtil ( &((*root)->child[ tolower( *word ) - 97 ]), minHeap, word + 1, dupWord ); else // The complete word is processed { // word is already present, increase the frequency if ( (*root)->isEnd ) ++( (*root)->frequency ); else { (*root)->isEnd = 1; (*root)->frequency = 1; } // Insert in min heap also insertInMinHeap( minHeap, root, dupWord ); }} // add a word to Trie & min heap. A wrapper over the insertUtilvoid insertTrieAndHeap(const char *word, TrieNode** root, MinHeap* minHeap){ insertUtil( root, minHeap, word, word );} // A utility function to show results, The min heap// contains k most frequent words so far, at any timevoid displayMinHeap( MinHeap* minHeap ){ int i; // print top K word with frequency for( i = 0; i < minHeap->count; ++i ) { printf( "%s : %d\n", minHeap->array[i].word, minHeap->array[i].frequency ); }} // The main function that takes a file as input, add words to heap// and Trie, finally shows result from heapvoid printKMostFreq( FILE* fp, int k ){ // Create a Min Heap of Size k MinHeap* minHeap = createMinHeap( k ); // Create an empty Trie TrieNode* root = NULL; // A buffer to store one word at a time char buffer[MAX_WORD_SIZE]; // Read words one by one from file. Insert the word in Trie and Min Heap while( fscanf( fp, "%s", buffer ) != EOF ) insertTrieAndHeap(buffer, &root, minHeap); // The Min Heap will have the k most frequent words, so print Min Heap nodes displayMinHeap( minHeap );} // Driver program to test above functionsint main(){ int k = 5; FILE *fp = fopen ("file.txt", "r"); if (fp == NULL) printf ("File doesn't exist "); else printKMostFreq (fp, k); return 0;}
Output:
your : 3
well : 3
and : 4
to : 4
Geeks : 6
The above output is for a file with following content.
Welcome to the world of Geeks
This portal has been created to provide well written well thought and well explained
solutions for selected questions If you like Geeks for Geeks and would like to contribute
here is your chance You can write article and mail your article to contribute at
geeksforgeeks org See your article appearing on the Geeks for Geeks main page and help
thousands of other Geeks
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
varshagumber28
Advanced Data Structure
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 2759,
"s": 54,
"text": "Given a book of words. Assume you have enough main memory to accommodate all words. design a data structure to find top K maximum occurring words. The data structure should be dynamic so that new words can be added. A simple solution is to use Hashing. Hash all words one by one in a hash table. If a word is already present, then increment its count. Finally, traverse through the hash table and return the k words with maximum counts.We can use Trie and Min Heap to get the k most frequent words efficiently. The idea is to use Trie for searching existing words adding new words efficiently. Trie also stores count of occurrences of words. A Min Heap of size k is used to keep track of k most frequent words at any point of time(Use of Min Heap is same as we used it to find k largest elements in this post). Trie and Min Heap are linked with each other by storing an additional field in Trie ‘indexMinHeap’ and a pointer ‘trNode’ in Min Heap. The value of ‘indexMinHeap’ is maintained as -1 for the words which are currently not in Min Heap (or currently not among the top k frequent words). For the words which are present in Min Heap, ‘indexMinHeap’ contains, index of the word in Min Heap. The pointer ‘trNode’ in Min Heap points to the leaf node corresponding to the word in Trie.Following is the complete process to print k most frequent words from a file.Read all words one by one. For every word, insert it into Trie. Increase the counter of the word, if already exists. Now, we need to insert this word in min heap also. For insertion in min heap, 3 cases arise:1. The word is already present. We just increase the corresponding frequency value in min heap and call minHeapify() for the index obtained by “indexMinHeap” field in Trie. When the min heap nodes are being swapped, we change the corresponding minHeapIndex in the Trie. Remember each node of the min heap is also having pointer to Trie leaf node.2. The minHeap is not full. we will insert the new word into min heap & update the root node in the min heap node & min heap index in Trie leaf node. Now, call buildMinHeap().3. The min heap is full. Two sub-cases arise. ....3.1 The frequency of the new word inserted is less than the frequency of the word stored in the head of min heap. Do nothing.....3.2 The frequency of the new word inserted is greater than the frequency of the word stored in the head of min heap. Replace & update the fields. Make sure to update the corresponding min heap index of the “word to be replaced” in Trie with -1 as the word is no longer in min heap.4. Finally, Min Heap will have the k most frequent words of all words present in given file. So we just need to print all words present in Min Heap. "
},
{
"code": null,
"e": 2765,
"s": 2761,
"text": "CPP"
},
{
"code": "// A program to find k most frequent words in a file#include <stdio.h>#include <string.h>#include <ctype.h> # define MAX_CHARS 26# define MAX_WORD_SIZE 30 // A Trie nodestruct TrieNode{ bool isEnd; // indicates end of word unsigned frequency; // the number of occurrences of a word int indexMinHeap; // the index of the word in minHeap TrieNode* child[MAX_CHARS]; // represents 26 slots each for 'a' to 'z'.}; // A Min Heap nodestruct MinHeapNode{ TrieNode* root; // indicates the leaf node of TRIE unsigned frequency; // number of occurrences char* word; // the actual word stored}; // A Min Heapstruct MinHeap{ unsigned capacity; // the total size a min heap int count; // indicates the number of slots filled. MinHeapNode* array; // represents the collection of minHeapNodes}; // A utility function to create a new Trie nodeTrieNode* newTrieNode(){ // Allocate memory for Trie Node TrieNode* trieNode = new TrieNode; // Initialize values for new node trieNode->isEnd = 0; trieNode->frequency = 0; trieNode->indexMinHeap = -1; for( int i = 0; i < MAX_CHARS; ++i ) trieNode->child[i] = NULL; return trieNode;} // A utility function to create a Min Heap of given capacityMinHeap* createMinHeap( int capacity ){ MinHeap* minHeap = new MinHeap; minHeap->capacity = capacity; minHeap->count = 0; // Allocate memory for array of min heap nodes minHeap->array = new MinHeapNode [ minHeap->capacity ]; return minHeap;} // A utility function to swap two min heap nodes. This function// is needed in minHeapifyvoid swapMinHeapNodes ( MinHeapNode* a, MinHeapNode* b ){ MinHeapNode temp = *a; *a = *b; *b = temp;} // This is the standard minHeapify function. It does one thing extra.// It updates the minHapIndex in Trie when two nodes are swapped in// in min heapvoid minHeapify( MinHeap* minHeap, int idx ){ int left, right, smallest; left = 2 * idx + 1; right = 2 * idx + 2; smallest = idx; if ( left < minHeap->count && minHeap->array[ left ]. frequency < minHeap->array[ smallest ]. frequency ) smallest = left; if ( right < minHeap->count && minHeap->array[ right ]. frequency < minHeap->array[ smallest ]. frequency ) smallest = right; if( smallest != idx ) { // Update the corresponding index in Trie node. minHeap->array[ smallest ]. root->indexMinHeap = idx; minHeap->array[ idx ]. root->indexMinHeap = smallest; // Swap nodes in min heap swapMinHeapNodes (&minHeap->array[ smallest ], &minHeap->array[ idx ]); minHeapify( minHeap, smallest ); }} // A standard function to build a heapvoid buildMinHeap( MinHeap* minHeap ){ int n, i; n = minHeap->count - 1; for( i = ( n - 1 ) / 2; i >= 0; --i ) minHeapify( minHeap, i );} // Inserts a word to heap, the function handles the 3 cases explained abovevoid insertInMinHeap( MinHeap* minHeap, TrieNode** root, const char* word ){ // Case 1: the word is already present in minHeap if( (*root)->indexMinHeap != -1 ) { ++( minHeap->array[ (*root)->indexMinHeap ]. frequency ); // percolate down minHeapify( minHeap, (*root)->indexMinHeap ); } // Case 2: Word is not present and heap is not full else if( minHeap->count < minHeap->capacity ) { int count = minHeap->count; minHeap->array[ count ]. frequency = (*root)->frequency; minHeap->array[ count ]. word = new char [strlen( word ) + 1]; strcpy( minHeap->array[ count ]. word, word ); minHeap->array[ count ]. root = *root; (*root)->indexMinHeap = minHeap->count; ++( minHeap->count ); buildMinHeap( minHeap ); } // Case 3: Word is not present and heap is full. And frequency of word // is more than root. The root is the least frequent word in heap, // replace root with new word else if ( (*root)->frequency > minHeap->array[0]. frequency ) { minHeap->array[ 0 ]. root->indexMinHeap = -1; minHeap->array[ 0 ]. root = *root; minHeap->array[ 0 ]. root->indexMinHeap = 0; minHeap->array[ 0 ]. frequency = (*root)->frequency; // delete previously allocated memory and delete [] minHeap->array[ 0 ]. word; minHeap->array[ 0 ]. word = new char [strlen( word ) + 1]; strcpy( minHeap->array[ 0 ]. word, word ); minHeapify ( minHeap, 0 ); }} // Inserts a new word to both Trie and Heapvoid insertUtil ( TrieNode** root, MinHeap* minHeap, const char* word, const char* dupWord ){ // Base Case if ( *root == NULL ) *root = newTrieNode(); // There are still more characters in word if ( *word != '\\0' ) insertUtil ( &((*root)->child[ tolower( *word ) - 97 ]), minHeap, word + 1, dupWord ); else // The complete word is processed { // word is already present, increase the frequency if ( (*root)->isEnd ) ++( (*root)->frequency ); else { (*root)->isEnd = 1; (*root)->frequency = 1; } // Insert in min heap also insertInMinHeap( minHeap, root, dupWord ); }} // add a word to Trie & min heap. A wrapper over the insertUtilvoid insertTrieAndHeap(const char *word, TrieNode** root, MinHeap* minHeap){ insertUtil( root, minHeap, word, word );} // A utility function to show results, The min heap// contains k most frequent words so far, at any timevoid displayMinHeap( MinHeap* minHeap ){ int i; // print top K word with frequency for( i = 0; i < minHeap->count; ++i ) { printf( \"%s : %d\\n\", minHeap->array[i].word, minHeap->array[i].frequency ); }} // The main function that takes a file as input, add words to heap// and Trie, finally shows result from heapvoid printKMostFreq( FILE* fp, int k ){ // Create a Min Heap of Size k MinHeap* minHeap = createMinHeap( k ); // Create an empty Trie TrieNode* root = NULL; // A buffer to store one word at a time char buffer[MAX_WORD_SIZE]; // Read words one by one from file. Insert the word in Trie and Min Heap while( fscanf( fp, \"%s\", buffer ) != EOF ) insertTrieAndHeap(buffer, &root, minHeap); // The Min Heap will have the k most frequent words, so print Min Heap nodes displayMinHeap( minHeap );} // Driver program to test above functionsint main(){ int k = 5; FILE *fp = fopen (\"file.txt\", \"r\"); if (fp == NULL) printf (\"File doesn't exist \"); else printKMostFreq (fp, k); return 0;}",
"e": 9412,
"s": 2765,
"text": null
},
{
"code": null,
"e": 9421,
"s": 9412,
"text": "Output: "
},
{
"code": null,
"e": 9464,
"s": 9421,
"text": "your : 3\nwell : 3\nand : 4\nto : 4\nGeeks : 6"
},
{
"code": null,
"e": 9520,
"s": 9464,
"text": "The above output is for a file with following content. "
},
{
"code": null,
"e": 9923,
"s": 9520,
"text": "Welcome to the world of Geeks \nThis portal has been created to provide well written well thought and well explained \nsolutions for selected questions If you like Geeks for Geeks and would like to contribute \nhere is your chance You can write article and mail your article to contribute at \ngeeksforgeeks org See your article appearing on the Geeks for Geeks main page and help \nthousands of other Geeks"
},
{
"code": null,
"e": 10049,
"s": 9923,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10062,
"s": 10049,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10077,
"s": 10062,
"text": "varshagumber28"
},
{
"code": null,
"e": 10101,
"s": 10077,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 10111,
"s": 10101,
"text": "Searching"
},
{
"code": null,
"e": 10121,
"s": 10111,
"text": "Searching"
}
]
|
How to Build a Simple Web Server with Node.js ? | 25 Jun, 2021
Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make a web server using node.js.
Creating Web Servers Using NodeJS: There are mainly two ways as follows.
Using http inbuilt moduleUsing express third party module
Using http inbuilt module
Using express third party module
Using http module: HTTP and HTTPS, these two inbuilt modules are used to create a simple server. The HTTPS module provides the feature of the encryption of communication with the help of the secure layer feature of this module. Whereas the HTTP module doesn’t provide the encryption of the data.
Project structure: It will look like this.
index.js
// Importing the http moduleconst http = require("http") // Creating server const server = http.createServer((req, res) => { // Sending the response res.write("This is the response from the server") res.end();}) // Server listening to port 3000server.listen((3000), () => { console.log("Server is Running");})
Run index.js file using below command:
node index.js
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Using express module: The express.js is one of the most powerful frameworks of the node.js that works on the upper layer of the http module. The main advantage of using express.js server is filtering the incoming requests by clients.
Installing module: Install the required module using the following command.
npm install express
Project structure: It will look like this.
index.js
// Importing express moduleconst express = require("express")const app = express() // Handling GET / requestapp.use("/", (req, res, next) => { res.send("This is the express server")}) // Handling GET /hello requestapp.get("/hello", (req, res, next) => { res.send("This is the hello response");}) // Server setupapp.listen(3000, () => { console.log("Server is Running")})
Run the index.js file using the below command:
node index.js
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 370,
"s": 28,
"text": "Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make a web server using node.js."
},
{
"code": null,
"e": 443,
"s": 370,
"text": "Creating Web Servers Using NodeJS: There are mainly two ways as follows."
},
{
"code": null,
"e": 501,
"s": 443,
"text": "Using http inbuilt moduleUsing express third party module"
},
{
"code": null,
"e": 527,
"s": 501,
"text": "Using http inbuilt module"
},
{
"code": null,
"e": 560,
"s": 527,
"text": "Using express third party module"
},
{
"code": null,
"e": 856,
"s": 560,
"text": "Using http module: HTTP and HTTPS, these two inbuilt modules are used to create a simple server. The HTTPS module provides the feature of the encryption of communication with the help of the secure layer feature of this module. Whereas the HTTP module doesn’t provide the encryption of the data."
},
{
"code": null,
"e": 899,
"s": 856,
"text": "Project structure: It will look like this."
},
{
"code": null,
"e": 908,
"s": 899,
"text": "index.js"
},
{
"code": "// Importing the http moduleconst http = require(\"http\") // Creating server const server = http.createServer((req, res) => { // Sending the response res.write(\"This is the response from the server\") res.end();}) // Server listening to port 3000server.listen((3000), () => { console.log(\"Server is Running\");})",
"e": 1232,
"s": 908,
"text": null
},
{
"code": null,
"e": 1271,
"s": 1232,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1285,
"s": 1271,
"text": "node index.js"
},
{
"code": null,
"e": 1384,
"s": 1285,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 1618,
"s": 1384,
"text": "Using express module: The express.js is one of the most powerful frameworks of the node.js that works on the upper layer of the http module. The main advantage of using express.js server is filtering the incoming requests by clients."
},
{
"code": null,
"e": 1694,
"s": 1618,
"text": "Installing module: Install the required module using the following command."
},
{
"code": null,
"e": 1714,
"s": 1694,
"text": "npm install express"
},
{
"code": null,
"e": 1757,
"s": 1714,
"text": "Project structure: It will look like this."
},
{
"code": null,
"e": 1766,
"s": 1757,
"text": "index.js"
},
{
"code": "// Importing express moduleconst express = require(\"express\")const app = express() // Handling GET / requestapp.use(\"/\", (req, res, next) => { res.send(\"This is the express server\")}) // Handling GET /hello requestapp.get(\"/hello\", (req, res, next) => { res.send(\"This is the hello response\");}) // Server setupapp.listen(3000, () => { console.log(\"Server is Running\")})",
"e": 2149,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2196,
"s": 2149,
"text": "Run the index.js file using the below command:"
},
{
"code": null,
"e": 2210,
"s": 2196,
"text": "node index.js"
},
{
"code": null,
"e": 2309,
"s": 2210,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2325,
"s": 2309,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 2342,
"s": 2325,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 2349,
"s": 2342,
"text": "Picked"
},
{
"code": null,
"e": 2357,
"s": 2349,
"text": "Node.js"
},
{
"code": null,
"e": 2374,
"s": 2357,
"text": "Web Technologies"
},
{
"code": null,
"e": 2472,
"s": 2374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2504,
"s": 2472,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2539,
"s": 2504,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2609,
"s": 2539,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 2636,
"s": 2609,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2661,
"s": 2636,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 2723,
"s": 2661,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2784,
"s": 2723,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2834,
"s": 2784,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2877,
"s": 2834,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Flyweight Design Pattern | 01 Sep, 2021
Flyweight pattern is one of the structural design patterns as this pattern provides ways to decrease object count thus improving application required objects structure. Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
Why do we care for number of objects in our program?
Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError.
Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects.
Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects.
In Flyweight pattern we use a HashMap that stores reference to the object which have already been created, every object is associated with a key. Now when a client wants to create an object, he simply has to pass a key associated with it and if the object has already been created we simply get the reference to that object else it creates a new object and then returns it reference to the client.
Intrinsic and Extrinsic States
To understand Intrinsic and Extrinsic state, let us consider an example.
Suppose in a text editor when we enter a character, an object of Character class is created, the attributes of the Character class are {name, font, size}. We do not need to create an object every time client enters a character since letter ‘B’ is no different from another ‘B’ . If client again types a ‘B’ we simply return the object which we have already created before. Now all these are intrinsic states (name, font, size), since they can be shared among the different objects as they are similar to each other.
Now we add to more attributes to the Character class, they are row and column. They specify the position of a character in the document. Now these attributes will not be similar even for same characters, since no two characters will have the same position in a document, these states are termed as extrinsic states, and they can’t be shared among objects.
Implementation : We implement the creation of Terrorists and Counter Terrorists In the game of Counter Strike. So we have 2 classes one for Terrorist(T) and other for Counter Terrorist(CT). Whenever a player asks for a weapon we assign him the asked weapon. In the mission, terrorist’s task is to plant a bomb while the counter terrorists have to diffuse the bomb.
Why to use Flyweight Design Pattern in this example? Here we use the Fly Weight design pattern, since here we need to reduce the object count for players. Now we have n number of players playing CS 1.6, if we do not follow the Fly Weight Design Pattern then we will have to create n number of objects, one for each player. But now we will only have to create 2 objects one for terrorists and other for counter terrorists, we will reuse then again and again whenever required.
Intrinsic State : Here ‘task’ is an intrinsic state for both types of players, since this is always same for T’s/CT’s. We can have some other states like their color or any other properties which are similar for all the Terrorists/Counter Terrorists in their respective Terrorists/Counter Terrorists class.
Extrinsic State : Weapon is an extrinsic state since each player can carry any weapon of his/her choice. Weapon need to be passed as a parameter by the client itself.
Class Diagram :
// A Java program to demonstrate working of// FlyWeight Pattern with example of Counter// Strike Gameimport java.util.Random;import java.util.HashMap; // A common interface for all playersinterface Player{ public void assignWeapon(String weapon); public void mission();} // Terrorist must have weapon and missionclass Terrorist implements Player{ // Intrinsic Attribute private final String TASK; // Extrinsic Attribute private String weapon; public Terrorist() { TASK = "PLANT A BOMB"; } public void assignWeapon(String weapon) { // Assign a weapon this.weapon = weapon; } public void mission() { //Work on the Mission System.out.println("Terrorist with weapon " + weapon + "|" + " Task is " + TASK); }} // CounterTerrorist must have weapon and missionclass CounterTerrorist implements Player{ // Intrinsic Attribute private final String TASK; // Extrinsic Attribute private String weapon; public CounterTerrorist() { TASK = "DIFFUSE BOMB"; } public void assignWeapon(String weapon) { this.weapon = weapon; } public void mission() { System.out.println("Counter Terrorist with weapon " + weapon + "|" + " Task is " + TASK); }} // Class used to get a player using HashMap (Returns// an existing player if a player of given type exists.// Else creates a new player and returns it.class PlayerFactory{ /* HashMap stores the reference to the object of Terrorist(TS) or CounterTerrorist(CT). */ private static HashMap <String, Player> hm = new HashMap<String, Player>(); // Method to get a player public static Player getPlayer(String type) { Player p = null; /* If an object for TS or CT has already been created simply return its reference */ if (hm.containsKey(type)) p = hm.get(type); else { /* create an object of TS/CT */ switch(type) { case "Terrorist": System.out.println("Terrorist Created"); p = new Terrorist(); break; case "CounterTerrorist": System.out.println("Counter Terrorist Created"); p = new CounterTerrorist(); break; default : System.out.println("Unreachable code!"); } // Once created insert it into the HashMap hm.put(type, p); } return p; }} // Driver classpublic class CounterStrike{ // All player types and weapon (used by getRandPlayerType() // and getRandWeapon() private static String[] playerType = {"Terrorist", "CounterTerrorist"}; private static String[] weapons = {"AK-47", "Maverick", "Gut Knife", "Desert Eagle"}; // Driver code public static void main(String args[]) { /* Assume that we have a total of 10 players in the game. */ for (int i = 0; i < 10; i++) { /* getPlayer() is called simply using the class name since the method is a static one */ Player p = PlayerFactory.getPlayer(getRandPlayerType()); /* Assign a weapon chosen randomly uniformly from the weapon array */ p.assignWeapon(getRandWeapon()); // Send this player on a mission p.mission(); } } // Utility methods to get a random player type and // weapon public static String getRandPlayerType() { Random r = new Random(); // Will return an integer between [0,2) int randInt = r.nextInt(playerType.length); // return the player stored at index 'randInt' return playerType[randInt]; } public static String getRandWeapon() { Random r = new Random(); // Will return an integer between [0,5) int randInt = r.nextInt(weapons.length); // Return the weapon stored at index 'randInt' return weapons[randInt]; }}
Output:
Counter Terrorist Created
Counter Terrorist with weapon Gut Knife| Task is DIFFUSE BOMB
Counter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB
Terrorist Created
Terrorist with weapon AK-47| Task is PLANT A BOMB
Terrorist with weapon Gut Knife| Task is PLANT A BOMB
Terrorist with weapon Gut Knife| Task is PLANT A BOMB
Terrorist with weapon Desert Eagle| Task is PLANT A BOMB
Terrorist with weapon AK-47| Task is PLANT A BOMB
Counter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB
Counter Terrorist with weapon Gut Knife| Task is DIFFUSE BOMB
Counter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB
Further Read – Flyweight Method in Python
References:
Elements of Reusable Object-Oriented Software(By Gang Of Four)
https://en.wikipedia.org/wiki/Flyweight_pattern
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
24ankitw
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 461,
"s": 54,
"text": "Flyweight pattern is one of the structural design patterns as this pattern provides ways to decrease object count thus improving application required objects structure. Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed."
},
{
"code": null,
"e": 514,
"s": 461,
"text": "Why do we care for number of objects in our program?"
},
{
"code": null,
"e": 657,
"s": 514,
"text": "Less number of objects reduces the memory usage, and it manages to keep us away from errors related to memory like java.lang.OutOfMemoryError."
},
{
"code": null,
"e": 783,
"s": 657,
"text": "Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects."
},
{
"code": null,
"e": 909,
"s": 783,
"text": "Although creating an object in Java is really fast, we can still reduce the execution time of our program by sharing objects."
},
{
"code": null,
"e": 1307,
"s": 909,
"text": "In Flyweight pattern we use a HashMap that stores reference to the object which have already been created, every object is associated with a key. Now when a client wants to create an object, he simply has to pass a key associated with it and if the object has already been created we simply get the reference to that object else it creates a new object and then returns it reference to the client."
},
{
"code": null,
"e": 1338,
"s": 1307,
"text": "Intrinsic and Extrinsic States"
},
{
"code": null,
"e": 1411,
"s": 1338,
"text": "To understand Intrinsic and Extrinsic state, let us consider an example."
},
{
"code": null,
"e": 1927,
"s": 1411,
"text": "Suppose in a text editor when we enter a character, an object of Character class is created, the attributes of the Character class are {name, font, size}. We do not need to create an object every time client enters a character since letter ‘B’ is no different from another ‘B’ . If client again types a ‘B’ we simply return the object which we have already created before. Now all these are intrinsic states (name, font, size), since they can be shared among the different objects as they are similar to each other."
},
{
"code": null,
"e": 2283,
"s": 1927,
"text": "Now we add to more attributes to the Character class, they are row and column. They specify the position of a character in the document. Now these attributes will not be similar even for same characters, since no two characters will have the same position in a document, these states are termed as extrinsic states, and they can’t be shared among objects."
},
{
"code": null,
"e": 2648,
"s": 2283,
"text": "Implementation : We implement the creation of Terrorists and Counter Terrorists In the game of Counter Strike. So we have 2 classes one for Terrorist(T) and other for Counter Terrorist(CT). Whenever a player asks for a weapon we assign him the asked weapon. In the mission, terrorist’s task is to plant a bomb while the counter terrorists have to diffuse the bomb."
},
{
"code": null,
"e": 3124,
"s": 2648,
"text": "Why to use Flyweight Design Pattern in this example? Here we use the Fly Weight design pattern, since here we need to reduce the object count for players. Now we have n number of players playing CS 1.6, if we do not follow the Fly Weight Design Pattern then we will have to create n number of objects, one for each player. But now we will only have to create 2 objects one for terrorists and other for counter terrorists, we will reuse then again and again whenever required."
},
{
"code": null,
"e": 3431,
"s": 3124,
"text": "Intrinsic State : Here ‘task’ is an intrinsic state for both types of players, since this is always same for T’s/CT’s. We can have some other states like their color or any other properties which are similar for all the Terrorists/Counter Terrorists in their respective Terrorists/Counter Terrorists class."
},
{
"code": null,
"e": 3598,
"s": 3431,
"text": "Extrinsic State : Weapon is an extrinsic state since each player can carry any weapon of his/her choice. Weapon need to be passed as a parameter by the client itself."
},
{
"code": null,
"e": 3614,
"s": 3598,
"text": "Class Diagram :"
},
{
"code": "// A Java program to demonstrate working of// FlyWeight Pattern with example of Counter// Strike Gameimport java.util.Random;import java.util.HashMap; // A common interface for all playersinterface Player{ public void assignWeapon(String weapon); public void mission();} // Terrorist must have weapon and missionclass Terrorist implements Player{ // Intrinsic Attribute private final String TASK; // Extrinsic Attribute private String weapon; public Terrorist() { TASK = \"PLANT A BOMB\"; } public void assignWeapon(String weapon) { // Assign a weapon this.weapon = weapon; } public void mission() { //Work on the Mission System.out.println(\"Terrorist with weapon \" + weapon + \"|\" + \" Task is \" + TASK); }} // CounterTerrorist must have weapon and missionclass CounterTerrorist implements Player{ // Intrinsic Attribute private final String TASK; // Extrinsic Attribute private String weapon; public CounterTerrorist() { TASK = \"DIFFUSE BOMB\"; } public void assignWeapon(String weapon) { this.weapon = weapon; } public void mission() { System.out.println(\"Counter Terrorist with weapon \" + weapon + \"|\" + \" Task is \" + TASK); }} // Class used to get a player using HashMap (Returns// an existing player if a player of given type exists.// Else creates a new player and returns it.class PlayerFactory{ /* HashMap stores the reference to the object of Terrorist(TS) or CounterTerrorist(CT). */ private static HashMap <String, Player> hm = new HashMap<String, Player>(); // Method to get a player public static Player getPlayer(String type) { Player p = null; /* If an object for TS or CT has already been created simply return its reference */ if (hm.containsKey(type)) p = hm.get(type); else { /* create an object of TS/CT */ switch(type) { case \"Terrorist\": System.out.println(\"Terrorist Created\"); p = new Terrorist(); break; case \"CounterTerrorist\": System.out.println(\"Counter Terrorist Created\"); p = new CounterTerrorist(); break; default : System.out.println(\"Unreachable code!\"); } // Once created insert it into the HashMap hm.put(type, p); } return p; }} // Driver classpublic class CounterStrike{ // All player types and weapon (used by getRandPlayerType() // and getRandWeapon() private static String[] playerType = {\"Terrorist\", \"CounterTerrorist\"}; private static String[] weapons = {\"AK-47\", \"Maverick\", \"Gut Knife\", \"Desert Eagle\"}; // Driver code public static void main(String args[]) { /* Assume that we have a total of 10 players in the game. */ for (int i = 0; i < 10; i++) { /* getPlayer() is called simply using the class name since the method is a static one */ Player p = PlayerFactory.getPlayer(getRandPlayerType()); /* Assign a weapon chosen randomly uniformly from the weapon array */ p.assignWeapon(getRandWeapon()); // Send this player on a mission p.mission(); } } // Utility methods to get a random player type and // weapon public static String getRandPlayerType() { Random r = new Random(); // Will return an integer between [0,2) int randInt = r.nextInt(playerType.length); // return the player stored at index 'randInt' return playerType[randInt]; } public static String getRandWeapon() { Random r = new Random(); // Will return an integer between [0,5) int randInt = r.nextInt(weapons.length); // Return the weapon stored at index 'randInt' return weapons[randInt]; }}",
"e": 7749,
"s": 3614,
"text": null
},
{
"code": null,
"e": 7759,
"s": 7751,
"text": "Output:"
},
{
"code": null,
"e": 8387,
"s": 7759,
"text": "Counter Terrorist Created\nCounter Terrorist with weapon Gut Knife| Task is DIFFUSE BOMB\nCounter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB\nTerrorist Created\nTerrorist with weapon AK-47| Task is PLANT A BOMB\nTerrorist with weapon Gut Knife| Task is PLANT A BOMB\nTerrorist with weapon Gut Knife| Task is PLANT A BOMB\nTerrorist with weapon Desert Eagle| Task is PLANT A BOMB\nTerrorist with weapon AK-47| Task is PLANT A BOMB\nCounter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB\nCounter Terrorist with weapon Gut Knife| Task is DIFFUSE BOMB\nCounter Terrorist with weapon Desert Eagle| Task is DIFFUSE BOMB"
},
{
"code": null,
"e": 8429,
"s": 8387,
"text": "Further Read – Flyweight Method in Python"
},
{
"code": null,
"e": 8441,
"s": 8429,
"text": "References:"
},
{
"code": null,
"e": 8504,
"s": 8441,
"text": "Elements of Reusable Object-Oriented Software(By Gang Of Four)"
},
{
"code": null,
"e": 8552,
"s": 8504,
"text": "https://en.wikipedia.org/wiki/Flyweight_pattern"
},
{
"code": null,
"e": 8821,
"s": 8552,
"text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8945,
"s": 8821,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 8954,
"s": 8945,
"text": "24ankitw"
},
{
"code": null,
"e": 8969,
"s": 8954,
"text": "Design Pattern"
}
]
|
Kafka Automation using Python with Real World Example | 03 Jan, 2022
Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. Apache Kafka lets you send and receive messages between various Microservices. Developing a scalable and reliable Automation Framework for Kafka-based Microservices Projects can be challenging sometimes.
In this article, we will see how to design a Kafka Automation Framework with Python for Microservices Architecture.
Basic knowledge of Microservices Architecture.
Good knowledge of Kafka Basic Concepts (e.g. Kafka Topics, Brokers, Partitions, Offset, Producer, Consumer, etc).
Good knowledge of Python Basics (pip install <package>, writing python methods).
We will go through a Real World scenario for Kafka Automation to understand the technical challenges and try to design our Automation Solution. Let’s imagine we are working on a Data Pipeline Project like the below Diagram. And We want to develop an Automation Framework for the same.
Various events (data) are coming from multiple Databases to our Kafka Topic. “Microservice 1A” consumes all such incoming messages and does some Processing and produces the Output in a different Kafka Topic.
The output of “Microservice 1A” is categorized into 2 different Kafka Topic, based on different requirements. Now, “Microservice 2A” consumes one of the Output Topic from “Microservice 1A”, then processes the data with some complex logic and Sends the final Data to the MongoDB cluster.
Alternatively, ” Microservice 3B” consumes from another Output Topic from Microservice 1A”, then, do some more processing and publish the output Data in the next Kafka Topic.
“Microservice 4B” consumes this data and after some more processing, it sends the final data to ElasticSearch Cluster.
We are trying to Design an Automation Framework that will validate all the Input and Output of these 4 Microservices. (These Microservices can be written in any Tech-Stacks like Java+SpringBoot Or C# DotNet Or Python+Django.)
We will design our Automation Framework using Python.
For now, let’s summarize a few major points based on our understanding of the above System Design.
We need to choose a suitable Kafka Library for our Automation Framework.
We need to develop the basic building block of Kafka automation i.e. Kafka Consumer with appropriate Kafka Configurations.
We need to carefully use the appropriate Kafka Offset commit mechanism to properly Test the Data.
We need to carefully handle Kafka Partition Rebalance if it happens during Automation execution.
We need to design our Test Cases for future Scalability requirements. (i.e. 1 Kafka Topic may contain 6 partitions and they are parallelly sending different kinds of data in those 6 partitions. We can execute 6 parallel Automation TCs for each of these 6 partitions)
While working on Kafka Automation with Python we have 3 popular choices of Libraries on the Internet.
PyKafkaKafka-pythonConfluent Kafka
PyKafka
Kafka-python
Confluent Kafka
Each of these Libraries has its own Pros and Cons So we will have chosen based on our Project Requirements.
Unlike most of the Kafka Python Tutorials available on the Internet, We will not work on localhost. Instead, We will try to connect to the Remote Kafka cluster with SSL Authentication.
For Internal Microservices (not exposed to Internet-facing End Users) We will see SSL as a popular Authentication mechanism with Kafka clusters. Most of the Companies use either Confluent Kafka clusters or Amazon MSK clusters (Managed Streaming Kafka is based on Apache Kafka).
In order to connect to Kafka clusters, We get 1 JKS File and one Password for this JKS file from the Infra Support Team. So our job is to convert this JKS file into the appropriate format (as expected by the Python Kafka Library).
If we are using Amazon MSK clusters then We can build our Automation Framework using PyKafka or Kafka-python (both are Open Source and most popular for Apache Kafka Automation). If we are using Confluent Kafka clusters then We have to use Confluent Kafka Library as we will get Library support for Confluent specific features like ksqlDB, REST Proxy, and Schema Registry. We will use Confluent Kafka Library for Python Automation as we can serve automation of both Apache Kafka cluster and Confluent Kafka cluster with this Library. We need Python 3.x and Pip already installed. We can execute the below command to install the Library in our System.
pip install confluent-kafka
We need to convert the JKS file (JKS not compatible with Python) into PKCS12 format in order to use it with Confluent Kafka Library.
JRE 8 or Above should be installed in the system.
We need to run “keytool” command Inside <JRE_install_path>/bin
So open CMD prompt, go to JRE_install_path>/bin
Step 1: Execute the below command to get the Alias name:
keytool -list -v -keystore <absolute_path_to_JKS_file>
(When asked we need to provide the password we received for the JKS file from our Infra Team)
Step 2: Execute the below command along with the Alias name we got from Step 1 output.
keytool -v -importkeystore -srckeystore <absolute_path_to_JKS_file> -srcalias <alias_name> -destkeystore certkey.p12 -deststoretype PKCS12
This will again ask for the source Keystore password and we must input the same password as Step 1.
After executing this command we will get the PKCS12 file (i.e. certkey.p12 ) in the current directory, we need to copy this file into our Automation Framework Directory. And we are good to start building our Automation Framework with Python.
Note: If we plan to use PyKafka or Kafka-python Library instead of Confluent Kafka then we need to generate PEM files from this PKCS12 file with some additional commands.
We will use the same PKCS12 file that was generated during JKS to PKCS conversion step mentioned above.
from confluent_kafka import Consumer
import time
print("Starting Kafka Consumer")
mysecret = "yourjksPassword"
#you can call remote API to get JKS password instead of hardcoding like above
conf = {
'bootstrap.servers' : 'm1.msk.us-east.aws.com:9094, m2.msk.us-east.aws.com:9094, m3.msk.us-east.aws.com:9094',
'group.id' : 'KfConsumer1',
'security.protocol' : 'SSL',
'auto.offset.reset' : 'earliest',
'enable.auto.commit' : True,
'max.poll.records' : 5,
'heartbeat.interval.ms' : 25000,
'max.poll.interval.ms' : 90000,
'session.timeout.ms' : 180000,
'ssl.keystore.password' : mysecret,
'ssl.keystore.location' : './certkey.p12'
}
print("connecting to Kafka topic")
consumer = Consumer(conf)
consumer.subscribe(['kf.topic.name'])
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
print("Consumer error happened: {}".format(msg.error()))
continue
print("Connected to Topic: {} and Partition : {}".format(msg.topic(), msg.partition() ))
print("Received Message : {} with Offset : {}".format(msg.value().decode('utf-8'), msg.offset() ))
time.sleep(2.5)
#consumer.close()
Sample Output of this Above Code :
Starting Kafka Consumer
connecting to Kafka topic
Connected to Topic: kf.topic.name and Partition : kf.topic.name-0
Received Message : abc101 with Offset : 0
Connected to Topic: kf.topic.name and Partition : kf.topic.name-1
Received Message : xyz201 with Offset : 0
Connected to Topic: kf.topic.name and Partition : kf.topic.name-0
Received Message : abc102 with Offset : 1
Connected to Topic: kf.topic.name and Partition : kf.topic.name-1
Received Message : xyz202 with Offset : 1
We know how to consume messages from Kafka Topic with SSL authentication.Going forward we can add our own logic to validate incoming messages in our Kafka Topic.
We can use other option of better offset management Example: ‘enable.auto.commit’ : FalseAnd Add custom code to Do Manual Commit of messages based on certain conditions.
We can simultaneously run this program in multiple Console Window to observe the Automatic Kafka Rebalance mechanism.Example: If our Kafka Topic has total 3 partitions and We are executing this same Code in 3 Consoles (i.e. 3 instances)Then, we might see each Instance is getting assigned 1 partition out of a total of 3 partitions.
This specific configuration ‘group.id’ : ‘KfConsumer1’ helps us to observe Kafka Partition rebalance in the above example (i.e. all 3 instances are having the same group.id mentioned)
We have got the basic building block of Kafka automation i.e. Kafka Python Consumer with appropriate Kafka Configurations. So we can extend this Code as per our Project needs and continue modifying and developing our Kafka Automation Framework.
kafka-python
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 320,
"s": 28,
"text": "Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. Apache Kafka lets you send and receive messages between various Microservices. Developing a scalable and reliable Automation Framework for Kafka-based Microservices Projects can be challenging sometimes."
},
{
"code": null,
"e": 438,
"s": 320,
"text": " In this article, we will see how to design a Kafka Automation Framework with Python for Microservices Architecture. "
},
{
"code": null,
"e": 485,
"s": 438,
"text": "Basic knowledge of Microservices Architecture."
},
{
"code": null,
"e": 599,
"s": 485,
"text": "Good knowledge of Kafka Basic Concepts (e.g. Kafka Topics, Brokers, Partitions, Offset, Producer, Consumer, etc)."
},
{
"code": null,
"e": 680,
"s": 599,
"text": "Good knowledge of Python Basics (pip install <package>, writing python methods)."
},
{
"code": null,
"e": 965,
"s": 680,
"text": "We will go through a Real World scenario for Kafka Automation to understand the technical challenges and try to design our Automation Solution. Let’s imagine we are working on a Data Pipeline Project like the below Diagram. And We want to develop an Automation Framework for the same."
},
{
"code": null,
"e": 1174,
"s": 965,
"text": "Various events (data) are coming from multiple Databases to our Kafka Topic. “Microservice 1A” consumes all such incoming messages and does some Processing and produces the Output in a different Kafka Topic."
},
{
"code": null,
"e": 1463,
"s": 1174,
"text": "The output of “Microservice 1A” is categorized into 2 different Kafka Topic, based on different requirements. Now, “Microservice 2A” consumes one of the Output Topic from “Microservice 1A”, then processes the data with some complex logic and Sends the final Data to the MongoDB cluster."
},
{
"code": null,
"e": 1638,
"s": 1463,
"text": "Alternatively, ” Microservice 3B” consumes from another Output Topic from Microservice 1A”, then, do some more processing and publish the output Data in the next Kafka Topic."
},
{
"code": null,
"e": 1757,
"s": 1638,
"text": "“Microservice 4B” consumes this data and after some more processing, it sends the final data to ElasticSearch Cluster."
},
{
"code": null,
"e": 1983,
"s": 1757,
"text": "We are trying to Design an Automation Framework that will validate all the Input and Output of these 4 Microservices. (These Microservices can be written in any Tech-Stacks like Java+SpringBoot Or C# DotNet Or Python+Django.)"
},
{
"code": null,
"e": 2037,
"s": 1983,
"text": "We will design our Automation Framework using Python."
},
{
"code": null,
"e": 2136,
"s": 2037,
"text": "For now, let’s summarize a few major points based on our understanding of the above System Design."
},
{
"code": null,
"e": 2209,
"s": 2136,
"text": "We need to choose a suitable Kafka Library for our Automation Framework."
},
{
"code": null,
"e": 2332,
"s": 2209,
"text": "We need to develop the basic building block of Kafka automation i.e. Kafka Consumer with appropriate Kafka Configurations."
},
{
"code": null,
"e": 2430,
"s": 2332,
"text": "We need to carefully use the appropriate Kafka Offset commit mechanism to properly Test the Data."
},
{
"code": null,
"e": 2527,
"s": 2430,
"text": "We need to carefully handle Kafka Partition Rebalance if it happens during Automation execution."
},
{
"code": null,
"e": 2794,
"s": 2527,
"text": "We need to design our Test Cases for future Scalability requirements. (i.e. 1 Kafka Topic may contain 6 partitions and they are parallelly sending different kinds of data in those 6 partitions. We can execute 6 parallel Automation TCs for each of these 6 partitions)"
},
{
"code": null,
"e": 2896,
"s": 2794,
"text": "While working on Kafka Automation with Python we have 3 popular choices of Libraries on the Internet."
},
{
"code": null,
"e": 2931,
"s": 2896,
"text": "PyKafkaKafka-pythonConfluent Kafka"
},
{
"code": null,
"e": 2939,
"s": 2931,
"text": "PyKafka"
},
{
"code": null,
"e": 2952,
"s": 2939,
"text": "Kafka-python"
},
{
"code": null,
"e": 2968,
"s": 2952,
"text": "Confluent Kafka"
},
{
"code": null,
"e": 3076,
"s": 2968,
"text": "Each of these Libraries has its own Pros and Cons So we will have chosen based on our Project Requirements."
},
{
"code": null,
"e": 3261,
"s": 3076,
"text": "Unlike most of the Kafka Python Tutorials available on the Internet, We will not work on localhost. Instead, We will try to connect to the Remote Kafka cluster with SSL Authentication."
},
{
"code": null,
"e": 3539,
"s": 3261,
"text": "For Internal Microservices (not exposed to Internet-facing End Users) We will see SSL as a popular Authentication mechanism with Kafka clusters. Most of the Companies use either Confluent Kafka clusters or Amazon MSK clusters (Managed Streaming Kafka is based on Apache Kafka)."
},
{
"code": null,
"e": 3770,
"s": 3539,
"text": "In order to connect to Kafka clusters, We get 1 JKS File and one Password for this JKS file from the Infra Support Team. So our job is to convert this JKS file into the appropriate format (as expected by the Python Kafka Library)."
},
{
"code": null,
"e": 4421,
"s": 3770,
"text": "If we are using Amazon MSK clusters then We can build our Automation Framework using PyKafka or Kafka-python (both are Open Source and most popular for Apache Kafka Automation). If we are using Confluent Kafka clusters then We have to use Confluent Kafka Library as we will get Library support for Confluent specific features like ksqlDB, REST Proxy, and Schema Registry. We will use Confluent Kafka Library for Python Automation as we can serve automation of both Apache Kafka cluster and Confluent Kafka cluster with this Library. We need Python 3.x and Pip already installed. We can execute the below command to install the Library in our System. "
},
{
"code": null,
"e": 4449,
"s": 4421,
"text": "pip install confluent-kafka"
},
{
"code": null,
"e": 4582,
"s": 4449,
"text": "We need to convert the JKS file (JKS not compatible with Python) into PKCS12 format in order to use it with Confluent Kafka Library."
},
{
"code": null,
"e": 4632,
"s": 4582,
"text": "JRE 8 or Above should be installed in the system."
},
{
"code": null,
"e": 4695,
"s": 4632,
"text": "We need to run “keytool” command Inside <JRE_install_path>/bin"
},
{
"code": null,
"e": 4743,
"s": 4695,
"text": "So open CMD prompt, go to JRE_install_path>/bin"
},
{
"code": null,
"e": 4800,
"s": 4743,
"text": "Step 1: Execute the below command to get the Alias name:"
},
{
"code": null,
"e": 4858,
"s": 4800,
"text": "keytool -list -v -keystore <absolute_path_to_JKS_file>"
},
{
"code": null,
"e": 4952,
"s": 4858,
"text": "(When asked we need to provide the password we received for the JKS file from our Infra Team)"
},
{
"code": null,
"e": 5039,
"s": 4952,
"text": "Step 2: Execute the below command along with the Alias name we got from Step 1 output."
},
{
"code": null,
"e": 5185,
"s": 5039,
"text": "keytool -v -importkeystore -srckeystore <absolute_path_to_JKS_file> -srcalias <alias_name> -destkeystore certkey.p12 -deststoretype PKCS12"
},
{
"code": null,
"e": 5285,
"s": 5185,
"text": "This will again ask for the source Keystore password and we must input the same password as Step 1."
},
{
"code": null,
"e": 5527,
"s": 5285,
"text": "After executing this command we will get the PKCS12 file (i.e. certkey.p12 ) in the current directory, we need to copy this file into our Automation Framework Directory. And we are good to start building our Automation Framework with Python."
},
{
"code": null,
"e": 5698,
"s": 5527,
"text": "Note: If we plan to use PyKafka or Kafka-python Library instead of Confluent Kafka then we need to generate PEM files from this PKCS12 file with some additional commands."
},
{
"code": null,
"e": 5802,
"s": 5698,
"text": "We will use the same PKCS12 file that was generated during JKS to PKCS conversion step mentioned above."
},
{
"code": null,
"e": 7051,
"s": 5802,
"text": "from confluent_kafka import Consumer\nimport time\n\nprint(\"Starting Kafka Consumer\")\n\nmysecret = \"yourjksPassword\"\n#you can call remote API to get JKS password instead of hardcoding like above\n\nconf = {\n 'bootstrap.servers' : 'm1.msk.us-east.aws.com:9094, m2.msk.us-east.aws.com:9094, m3.msk.us-east.aws.com:9094',\n 'group.id' : 'KfConsumer1',\n 'security.protocol' : 'SSL',\n 'auto.offset.reset' : 'earliest',\n 'enable.auto.commit' : True,\n 'max.poll.records' : 5,\n 'heartbeat.interval.ms' : 25000,\n 'max.poll.interval.ms' : 90000,\n 'session.timeout.ms' : 180000,\n 'ssl.keystore.password' : mysecret,\n 'ssl.keystore.location' : './certkey.p12'\n }\n\nprint(\"connecting to Kafka topic\")\n\nconsumer = Consumer(conf)\n\nconsumer.subscribe(['kf.topic.name'])\nwhile True:\n msg = consumer.poll(1.0)\n \n if msg is None:\n continue\n if msg.error():\n print(\"Consumer error happened: {}\".format(msg.error()))\n continue\n print(\"Connected to Topic: {} and Partition : {}\".format(msg.topic(), msg.partition() ))\n print(\"Received Message : {} with Offset : {}\".format(msg.value().decode('utf-8'), msg.offset() ))\n time.sleep(2.5)\n#consumer.close()"
},
{
"code": null,
"e": 7086,
"s": 7051,
"text": "Sample Output of this Above Code :"
},
{
"code": null,
"e": 7620,
"s": 7086,
"text": "Starting Kafka Consumer\nconnecting to Kafka topic\nConnected to Topic: kf.topic.name and Partition : kf.topic.name-0\nReceived Message : abc101 with Offset : 0\nConnected to Topic: kf.topic.name and Partition : kf.topic.name-1\nReceived Message : xyz201 with Offset : 0\nConnected to Topic: kf.topic.name and Partition : kf.topic.name-0\nReceived Message : abc102 with Offset : 1\nConnected to Topic: kf.topic.name and Partition : kf.topic.name-1\nReceived Message : xyz202 with Offset : 1"
},
{
"code": null,
"e": 7782,
"s": 7620,
"text": "We know how to consume messages from Kafka Topic with SSL authentication.Going forward we can add our own logic to validate incoming messages in our Kafka Topic."
},
{
"code": null,
"e": 7958,
"s": 7782,
"text": "We can use other option of better offset management Example: ‘enable.auto.commit’ : FalseAnd Add custom code to Do Manual Commit of messages based on certain conditions."
},
{
"code": null,
"e": 8291,
"s": 7958,
"text": "We can simultaneously run this program in multiple Console Window to observe the Automatic Kafka Rebalance mechanism.Example: If our Kafka Topic has total 3 partitions and We are executing this same Code in 3 Consoles (i.e. 3 instances)Then, we might see each Instance is getting assigned 1 partition out of a total of 3 partitions."
},
{
"code": null,
"e": 8475,
"s": 8291,
"text": "This specific configuration ‘group.id’ : ‘KfConsumer1’ helps us to observe Kafka Partition rebalance in the above example (i.e. all 3 instances are having the same group.id mentioned)"
},
{
"code": null,
"e": 8720,
"s": 8475,
"text": "We have got the basic building block of Kafka automation i.e. Kafka Python Consumer with appropriate Kafka Configurations. So we can extend this Code as per our Project needs and continue modifying and developing our Kafka Automation Framework."
},
{
"code": null,
"e": 8733,
"s": 8720,
"text": "kafka-python"
},
{
"code": null,
"e": 8740,
"s": 8733,
"text": "Python"
},
{
"code": null,
"e": 8838,
"s": 8740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8870,
"s": 8838,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8897,
"s": 8870,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8928,
"s": 8897,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8949,
"s": 8928,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8972,
"s": 8949,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9028,
"s": 8972,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 9070,
"s": 9028,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 9112,
"s": 9070,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 9151,
"s": 9112,
"text": "Python | Get unique values from a list"
}
]
|
Python program to convert binary to ASCII | 31 Aug, 2021
In this article, we are going to see the conversion of Binary to ASCII in the Python programming language. There are multiple approaches by which this conversion can be performed that are illustrated below:
Binascii helps convert between binary and various ASCII-encoded binary representations.
b2a_uu() function: Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program.
The b2a_uu() function is used to convert the specified binary string to its corresponding ASCII equivalent.
Syntax: b2a_uu(Text)
Parameter: This function accepts a single parameter which is illustrated below:
Text: This is the specified binary string that is going to be converted into its ASCII equivalent.
Return Values: This function returns the ASCII equivalent.
Python3
# Python program to illustrate the# conversion of Binary to ASCII # Importing binascii moduleimport binascii # Initializing a binary stringText = b"GFG is a CS Portal" # Calling the b2a_uu() function to# Convert the binary string to asciiAscii = binascii.b2a_uu(Text) # Getting the ASCII equivalentprint(Ascii)
Output:
b"21T9'(&ES(&$@0U,@4&]R=&%L\n"
Here we will use a built-in type to convert binary to ASCII value.
Firstly, call int(binary_sting, base) with the base as 2 indicating the binary string. and then call int.to_bytes(byte_number, byte_order) function, where byte_order is taken as “big” and byte_number is taken as the number of bytes that binary_int occupies to return an array of bytes. This byte_number can be found using the operation binary_int.bit_length() + 7 // 8. And then call array.decode operation to turn the array into ASCII text.
Python3
# Python program to illustrate the# conversion of Binary to ASCII # Initializing a binary string in the form of# 0 and 1, with base of 2binary_int = int("11000010110001001100011", 2); # Getting the byte numberbyte_number = binary_int.bit_length() + 7 // 8 # Getting an array of bytesbinary_array = binary_int.to_bytes(byte_number, "big") # Converting the array into ASCII textascii_text = binary_array.decode() # Getting the ASCII valueprint(ascii_text)
Output:
abc
Picked
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 261,
"s": 54,
"text": "In this article, we are going to see the conversion of Binary to ASCII in the Python programming language. There are multiple approaches by which this conversion can be performed that are illustrated below:"
},
{
"code": null,
"e": 349,
"s": 261,
"text": "Binascii helps convert between binary and various ASCII-encoded binary representations."
},
{
"code": null,
"e": 533,
"s": 349,
"text": "b2a_uu() function: Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program."
},
{
"code": null,
"e": 641,
"s": 533,
"text": "The b2a_uu() function is used to convert the specified binary string to its corresponding ASCII equivalent."
},
{
"code": null,
"e": 662,
"s": 641,
"text": "Syntax: b2a_uu(Text)"
},
{
"code": null,
"e": 742,
"s": 662,
"text": "Parameter: This function accepts a single parameter which is illustrated below:"
},
{
"code": null,
"e": 841,
"s": 742,
"text": "Text: This is the specified binary string that is going to be converted into its ASCII equivalent."
},
{
"code": null,
"e": 900,
"s": 841,
"text": "Return Values: This function returns the ASCII equivalent."
},
{
"code": null,
"e": 908,
"s": 900,
"text": "Python3"
},
{
"code": "# Python program to illustrate the# conversion of Binary to ASCII # Importing binascii moduleimport binascii # Initializing a binary stringText = b\"GFG is a CS Portal\" # Calling the b2a_uu() function to# Convert the binary string to asciiAscii = binascii.b2a_uu(Text) # Getting the ASCII equivalentprint(Ascii)",
"e": 1223,
"s": 908,
"text": null
},
{
"code": null,
"e": 1231,
"s": 1223,
"text": "Output:"
},
{
"code": null,
"e": 1262,
"s": 1231,
"text": "b\"21T9'(&ES(&$@0U,@4&]R=&%L\\n\""
},
{
"code": null,
"e": 1329,
"s": 1262,
"text": "Here we will use a built-in type to convert binary to ASCII value."
},
{
"code": null,
"e": 1771,
"s": 1329,
"text": "Firstly, call int(binary_sting, base) with the base as 2 indicating the binary string. and then call int.to_bytes(byte_number, byte_order) function, where byte_order is taken as “big” and byte_number is taken as the number of bytes that binary_int occupies to return an array of bytes. This byte_number can be found using the operation binary_int.bit_length() + 7 // 8. And then call array.decode operation to turn the array into ASCII text."
},
{
"code": null,
"e": 1779,
"s": 1771,
"text": "Python3"
},
{
"code": "# Python program to illustrate the# conversion of Binary to ASCII # Initializing a binary string in the form of# 0 and 1, with base of 2binary_int = int(\"11000010110001001100011\", 2); # Getting the byte numberbyte_number = binary_int.bit_length() + 7 // 8 # Getting an array of bytesbinary_array = binary_int.to_bytes(byte_number, \"big\") # Converting the array into ASCII textascii_text = binary_array.decode() # Getting the ASCII valueprint(ascii_text)",
"e": 2238,
"s": 1779,
"text": null
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Output:"
},
{
"code": null,
"e": 2250,
"s": 2246,
"text": "abc"
},
{
"code": null,
"e": 2257,
"s": 2250,
"text": "Picked"
},
{
"code": null,
"e": 2280,
"s": 2257,
"text": "Python string-programs"
},
{
"code": null,
"e": 2287,
"s": 2280,
"text": "Python"
},
{
"code": null,
"e": 2303,
"s": 2287,
"text": "Python Programs"
}
]
|
Software Testing | Configuration Testing | 08 May, 2019
Configuration Testing is the type of Software Testing which verifies the performance of the system under development against various combinations of software and hardware to find out the best configuration under which the system can work without any flaws or issues while matching its functional requirements.
Configuration Testing is the process of testing the system under each configuration of the supported software and hardware. Here, the different configurations of hardware and software means the multiple operating system versions, various browsers, various supported drivers, distinct memory sizes, different hard drive types, various types of CPU etc.
Various Configurations:
Operating System Configuration:Win XP, Win 7 32/64 bit, Win 8 32/64 bit, Win 10 etc.
Win XP, Win 7 32/64 bit, Win 8 32/64 bit, Win 10 etc.
Database Configuration:Oracle, DB2, MySql, MSSQL Server, Sybase etc.
Oracle, DB2, MySql, MSSQL Server, Sybase etc.
Browser Configuration:IE 8, IE 9, FF 16.0, Chrome, Microsoft Edge etc.
IE 8, IE 9, FF 16.0, Chrome, Microsoft Edge etc.
Objectives of Configuration Testing:The objective of configuration testing is:
To determine whether the software application fulfills the configurability requirements.
To identify the defects that were not efficiently found during different testing processes.
To determine an optimal configuration of the application under test.
To do analyse of the performance of software application by changing the hardware and software resources.
To do analyse of the system efficiency based on the prioritization.
To verify the degree of ease to how the bugs are reproducible irrespective of the configuration changes.
Configuration Testing Process:
Types of Configuration Testing:Configuration testing is of 2 types:
Software Configuration Testing:Software configuration testing is done over the Application Under Test with various operating system versions and various browser versions etc. It is a time consuming testing as it takes long time to install and uninstall the various software which are to be used for testing. When the build is released, software configuration begins after passing through the unit test and integration test.Hardware Configuration Testing:Hardware configuration testing is typically performed in labs where physical machines are used with various hardware connected to them.When a build is released, the software is installed in all the physical machines to which the hardware is attached and the test is carried out on each and every machine to confirm that the application is working fine. While doing hardware configuration test, the kind of hardware to be tested is spelled out and there are several computer hardware and peripherals which make it next to impossible to execute all the tests.
Software Configuration Testing:Software configuration testing is done over the Application Under Test with various operating system versions and various browser versions etc. It is a time consuming testing as it takes long time to install and uninstall the various software which are to be used for testing. When the build is released, software configuration begins after passing through the unit test and integration test.
Hardware Configuration Testing:Hardware configuration testing is typically performed in labs where physical machines are used with various hardware connected to them.When a build is released, the software is installed in all the physical machines to which the hardware is attached and the test is carried out on each and every machine to confirm that the application is working fine. While doing hardware configuration test, the kind of hardware to be tested is spelled out and there are several computer hardware and peripherals which make it next to impossible to execute all the tests.
Configuration Testing can also be classified into following 2 types:
Client level Testing:Client level testing is associated with the usability and functionality testing. This testing is done from the point of view of its direct interest of the users.Server level Testing:Server level testing is carried out to determine the communication between the software and the external environment when it is planned to be integrated after the release.
Client level Testing:Client level testing is associated with the usability and functionality testing. This testing is done from the point of view of its direct interest of the users.
Server level Testing:Server level testing is carried out to determine the communication between the software and the external environment when it is planned to be integrated after the release.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Software Requirement Specification (SRS) Format
Software Engineering | Classical Waterfall Model
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between Spring and Spring Boot
Unit Testing | Software Testing
Difference between IAAS, PAAS and SAAS
Difference Between Edge Computing and Fog Computing | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 May, 2019"
},
{
"code": null,
"e": 338,
"s": 28,
"text": "Configuration Testing is the type of Software Testing which verifies the performance of the system under development against various combinations of software and hardware to find out the best configuration under which the system can work without any flaws or issues while matching its functional requirements."
},
{
"code": null,
"e": 690,
"s": 338,
"text": "Configuration Testing is the process of testing the system under each configuration of the supported software and hardware. Here, the different configurations of hardware and software means the multiple operating system versions, various browsers, various supported drivers, distinct memory sizes, different hard drive types, various types of CPU etc."
},
{
"code": null,
"e": 714,
"s": 690,
"text": "Various Configurations:"
},
{
"code": null,
"e": 800,
"s": 714,
"text": "Operating System Configuration:Win XP, Win 7 32/64 bit, Win 8 32/64 bit, Win 10 etc. "
},
{
"code": null,
"e": 855,
"s": 800,
"text": "Win XP, Win 7 32/64 bit, Win 8 32/64 bit, Win 10 etc. "
},
{
"code": null,
"e": 925,
"s": 855,
"text": "Database Configuration:Oracle, DB2, MySql, MSSQL Server, Sybase etc. "
},
{
"code": null,
"e": 972,
"s": 925,
"text": "Oracle, DB2, MySql, MSSQL Server, Sybase etc. "
},
{
"code": null,
"e": 1044,
"s": 972,
"text": "Browser Configuration:IE 8, IE 9, FF 16.0, Chrome, Microsoft Edge etc. "
},
{
"code": null,
"e": 1094,
"s": 1044,
"text": "IE 8, IE 9, FF 16.0, Chrome, Microsoft Edge etc. "
},
{
"code": null,
"e": 1173,
"s": 1094,
"text": "Objectives of Configuration Testing:The objective of configuration testing is:"
},
{
"code": null,
"e": 1262,
"s": 1173,
"text": "To determine whether the software application fulfills the configurability requirements."
},
{
"code": null,
"e": 1354,
"s": 1262,
"text": "To identify the defects that were not efficiently found during different testing processes."
},
{
"code": null,
"e": 1423,
"s": 1354,
"text": "To determine an optimal configuration of the application under test."
},
{
"code": null,
"e": 1529,
"s": 1423,
"text": "To do analyse of the performance of software application by changing the hardware and software resources."
},
{
"code": null,
"e": 1597,
"s": 1529,
"text": "To do analyse of the system efficiency based on the prioritization."
},
{
"code": null,
"e": 1702,
"s": 1597,
"text": "To verify the degree of ease to how the bugs are reproducible irrespective of the configuration changes."
},
{
"code": null,
"e": 1733,
"s": 1702,
"text": "Configuration Testing Process:"
},
{
"code": null,
"e": 1801,
"s": 1733,
"text": "Types of Configuration Testing:Configuration testing is of 2 types:"
},
{
"code": null,
"e": 2813,
"s": 1801,
"text": "Software Configuration Testing:Software configuration testing is done over the Application Under Test with various operating system versions and various browser versions etc. It is a time consuming testing as it takes long time to install and uninstall the various software which are to be used for testing. When the build is released, software configuration begins after passing through the unit test and integration test.Hardware Configuration Testing:Hardware configuration testing is typically performed in labs where physical machines are used with various hardware connected to them.When a build is released, the software is installed in all the physical machines to which the hardware is attached and the test is carried out on each and every machine to confirm that the application is working fine. While doing hardware configuration test, the kind of hardware to be tested is spelled out and there are several computer hardware and peripherals which make it next to impossible to execute all the tests."
},
{
"code": null,
"e": 3237,
"s": 2813,
"text": "Software Configuration Testing:Software configuration testing is done over the Application Under Test with various operating system versions and various browser versions etc. It is a time consuming testing as it takes long time to install and uninstall the various software which are to be used for testing. When the build is released, software configuration begins after passing through the unit test and integration test."
},
{
"code": null,
"e": 3826,
"s": 3237,
"text": "Hardware Configuration Testing:Hardware configuration testing is typically performed in labs where physical machines are used with various hardware connected to them.When a build is released, the software is installed in all the physical machines to which the hardware is attached and the test is carried out on each and every machine to confirm that the application is working fine. While doing hardware configuration test, the kind of hardware to be tested is spelled out and there are several computer hardware and peripherals which make it next to impossible to execute all the tests."
},
{
"code": null,
"e": 3895,
"s": 3826,
"text": "Configuration Testing can also be classified into following 2 types:"
},
{
"code": null,
"e": 4270,
"s": 3895,
"text": "Client level Testing:Client level testing is associated with the usability and functionality testing. This testing is done from the point of view of its direct interest of the users.Server level Testing:Server level testing is carried out to determine the communication between the software and the external environment when it is planned to be integrated after the release."
},
{
"code": null,
"e": 4453,
"s": 4270,
"text": "Client level Testing:Client level testing is associated with the usability and functionality testing. This testing is done from the point of view of its direct interest of the users."
},
{
"code": null,
"e": 4646,
"s": 4453,
"text": "Server level Testing:Server level testing is carried out to determine the communication between the software and the external environment when it is planned to be integrated after the release."
},
{
"code": null,
"e": 4663,
"s": 4646,
"text": "Software Testing"
},
{
"code": null,
"e": 4684,
"s": 4663,
"text": "Software Engineering"
},
{
"code": null,
"e": 4782,
"s": 4684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4824,
"s": 4782,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 4872,
"s": 4824,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 4920,
"s": 4872,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 4969,
"s": 4920,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 5025,
"s": 4969,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 5060,
"s": 5025,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 5102,
"s": 5060,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 5134,
"s": 5102,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 5173,
"s": 5134,
"text": "Difference between IAAS, PAAS and SAAS"
}
]
|
Introduction to Ant Colony Optimization | 17 May, 2020
The algorithmic world is beautiful with multifarious strategies and tools being developed round the clock to render to the need for high-performance computing. In fact, when algorithms are inspired by natural laws, interesting results are observed. Evolutionary algorithms belong to such a class of algorithms. These algorithms are designed so as to mimic certain behaviours as well as evolutionary traits of the human genome. Moreover, such algorithmic design is not only constrained to humans but can be inspired by the natural behaviour of certain animals as well. The basic aim of fabricating such methodologies is to provide realistic, relevant and yet some low-cost solutions to problems that are hitherto unsolvable by conventional means.
Different optimization techniques have thus evolved based on such evolutionary algorithms and thereby opened up the domain of metaheuristics. Metaheuristic has been derived from two Greek words, namely, Meta meaning one level above and heuriskein meaning to find. Algorithms such as the Particle Swarm Optimization (PSO) and Ant Colony Optimization (ACO) are examples of swarm intelligence and metaheuristics. The goal of swarm intelligence is to design intelligent multi-agent systems by taking inspiration from the collective behaviour of social insects such as ants, termites, bees, wasps, and other animal societies such as flocks of birds or schools of fish.
Background:
Ant Colony Optimization technique is purely inspired from the foraging behaviour of ant colonies, first introduced by Marco Dorigo in the 1990s. Ants are eusocial insects that prefer community survival and sustaining rather than as individual species. They communicate with each other using sound, touch and pheromone. Pheromones are organic chemical compounds secreted by the ants that trigger a social response in members of same species. These are chemicals capable of acting like hormones outside the body of the secreting individual, to impact the behaviour of the receiving individuals. Since most ants live on the ground, they use the soil surface to leave pheromone trails that may be followed (smelled) by other ants.Ants live in community nests and the underlying principle of ACO is to observe the movement of the ants from their nests in order to search for food in the shortest possible path. Initially, ants start to move randomly in search of food around their nests. This randomized search opens up multiple routes from the nest to the food source. Now, based on the quality and quantity of the food, ants carry a portion of the food back with necessary pheromone concentration on its return path. Depending on these pheromone trials, the probability of selection of a specific path by the following ants would be a guiding factor to the food source. Evidently, this probability is based on the concentration as well as the rate of evaporation of pheromone. It can also be observed that since the evaporation rate of pheromone is also a deciding factor, the length of each path can easily be accounted for.
In the above figure, for simplicity, only two possible paths have been considered between the food source and the ant nest. The stages can be analyzed as follows:
Stage 1: All ants are in their nest. There is no pheromone content in the environment. (For algorithmic design, residual pheromone amount can be considered without interfering with the probability)Stage 2: Ants begin their search with equal (0.5 each) probability along each path. Clearly, the curved path is the longer and hence the time taken by ants to reach food source is greater than the other.Stage 3: The ants through the shorter path reaches food source earlier. Now, evidently they face with a similar selection dilemma, but this time due to pheromone trail along the shorter path already available, probability of selection is higher.Stage 4: More ants return via the shorter path and subsequently the pheromone concentrations also increase. Moreover, due to evaporation, the pheromone concentration in the longer path reduces, decreasing the probability of selection of this path in further stages. Therefore, the whole colony gradually uses the shorter path in higher probabilities. So, path optimization is attained.
Stage 1: All ants are in their nest. There is no pheromone content in the environment. (For algorithmic design, residual pheromone amount can be considered without interfering with the probability)
Stage 2: Ants begin their search with equal (0.5 each) probability along each path. Clearly, the curved path is the longer and hence the time taken by ants to reach food source is greater than the other.
Stage 3: The ants through the shorter path reaches food source earlier. Now, evidently they face with a similar selection dilemma, but this time due to pheromone trail along the shorter path already available, probability of selection is higher.
Stage 4: More ants return via the shorter path and subsequently the pheromone concentrations also increase. Moreover, due to evaporation, the pheromone concentration in the longer path reduces, decreasing the probability of selection of this path in further stages. Therefore, the whole colony gradually uses the shorter path in higher probabilities. So, path optimization is attained.
Algorithmic Design:
Pertaining to the above behaviour of the ants, an algorithmic design can now be developed. For simplicity, a single food source and single ant colony have been considered with just two paths of possible traversal. The whole scenario can be realized through weighted graphs where the ant colony and the food source act as vertices (or nodes); the paths serve as the edges and the pheromone values are the weights associated with the edges.Let the graph be G = (V, E) where V, E are the edges and the vertices of the graph. The vertices according to our consideration are Vs (Source vertex – ant colony) and Vd (Destination vertex – Food source), The two edges are E1 and E2 with lengths L1 and L2 assigned to each. Now, the associated pheromone values (indicative of their strength) can be assumed to be R1 and R2 for vertices E1 and E2 respectively. Thus for each ant, the starting probability of selection of path (between E1 and E2) can be expressed as follows:
Evidently, if R1>R2, the probability of choosing E1 is higher and vice-versa. Now, while returning through this shortest path say Ei, the pheromone value is updated for the corresponding path. The updation is done based on the length of the paths as well as the evaporation rate of pheromone. So, the update can be step-wise realized as follows:
In accordance to path length –In the above updation, i = 1, 2 and ‘K’ serves as a parameter of the model. Moreover, the update is dependent on the length of the path. Shorter the path, higher the pheromone added.In accordance to evaporation rate of pheromone –The parameter ‘v’ belongs to interval (0, 1] that regulates the pheromone evaporation. Further, i = 1, 2.
In accordance to path length –In the above updation, i = 1, 2 and ‘K’ serves as a parameter of the model. Moreover, the update is dependent on the length of the path. Shorter the path, higher the pheromone added.
In accordance to evaporation rate of pheromone –The parameter ‘v’ belongs to interval (0, 1] that regulates the pheromone evaporation. Further, i = 1, 2.
At each iteration, all ants are placed at source vertex Vs (ant colony). Subsequently, ants move from Vs to Vd (food source) following step 1. Next, all ants conduct their return trip and reinforce their chosen path based on step 2.
Pseudocode:
Procedure AntColonyOptimization:
Initialize necessary parameters and pheromone trials;
while not termination do:
Generate ant population;
Calculate fitness values associated with each ant;
Find best solution through selection methods;
Update pheromone trial;
end while
end procedure
The pheromone update and the fitness calculations in the above pseudocode can be found through the step-wise implementations mentioned above.Thus, the introduction of the ACO optimization technique has been established. The application of the ACO can be extended to various problems such as the famous TSP (Travelling Salesman Problem).
References:https://www.ics.uci.edu/~welling/teaching/271fall09/antcolonyopt.pdf
Artificial Intelligence
Genetic Algorithms
Machine Learning
Write From Home
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 798,
"s": 52,
"text": "The algorithmic world is beautiful with multifarious strategies and tools being developed round the clock to render to the need for high-performance computing. In fact, when algorithms are inspired by natural laws, interesting results are observed. Evolutionary algorithms belong to such a class of algorithms. These algorithms are designed so as to mimic certain behaviours as well as evolutionary traits of the human genome. Moreover, such algorithmic design is not only constrained to humans but can be inspired by the natural behaviour of certain animals as well. The basic aim of fabricating such methodologies is to provide realistic, relevant and yet some low-cost solutions to problems that are hitherto unsolvable by conventional means."
},
{
"code": null,
"e": 1462,
"s": 798,
"text": "Different optimization techniques have thus evolved based on such evolutionary algorithms and thereby opened up the domain of metaheuristics. Metaheuristic has been derived from two Greek words, namely, Meta meaning one level above and heuriskein meaning to find. Algorithms such as the Particle Swarm Optimization (PSO) and Ant Colony Optimization (ACO) are examples of swarm intelligence and metaheuristics. The goal of swarm intelligence is to design intelligent multi-agent systems by taking inspiration from the collective behaviour of social insects such as ants, termites, bees, wasps, and other animal societies such as flocks of birds or schools of fish."
},
{
"code": null,
"e": 1474,
"s": 1462,
"text": "Background:"
},
{
"code": null,
"e": 3097,
"s": 1474,
"text": "Ant Colony Optimization technique is purely inspired from the foraging behaviour of ant colonies, first introduced by Marco Dorigo in the 1990s. Ants are eusocial insects that prefer community survival and sustaining rather than as individual species. They communicate with each other using sound, touch and pheromone. Pheromones are organic chemical compounds secreted by the ants that trigger a social response in members of same species. These are chemicals capable of acting like hormones outside the body of the secreting individual, to impact the behaviour of the receiving individuals. Since most ants live on the ground, they use the soil surface to leave pheromone trails that may be followed (smelled) by other ants.Ants live in community nests and the underlying principle of ACO is to observe the movement of the ants from their nests in order to search for food in the shortest possible path. Initially, ants start to move randomly in search of food around their nests. This randomized search opens up multiple routes from the nest to the food source. Now, based on the quality and quantity of the food, ants carry a portion of the food back with necessary pheromone concentration on its return path. Depending on these pheromone trials, the probability of selection of a specific path by the following ants would be a guiding factor to the food source. Evidently, this probability is based on the concentration as well as the rate of evaporation of pheromone. It can also be observed that since the evaporation rate of pheromone is also a deciding factor, the length of each path can easily be accounted for."
},
{
"code": null,
"e": 3260,
"s": 3097,
"text": "In the above figure, for simplicity, only two possible paths have been considered between the food source and the ant nest. The stages can be analyzed as follows:"
},
{
"code": null,
"e": 4291,
"s": 3260,
"text": "Stage 1: All ants are in their nest. There is no pheromone content in the environment. (For algorithmic design, residual pheromone amount can be considered without interfering with the probability)Stage 2: Ants begin their search with equal (0.5 each) probability along each path. Clearly, the curved path is the longer and hence the time taken by ants to reach food source is greater than the other.Stage 3: The ants through the shorter path reaches food source earlier. Now, evidently they face with a similar selection dilemma, but this time due to pheromone trail along the shorter path already available, probability of selection is higher.Stage 4: More ants return via the shorter path and subsequently the pheromone concentrations also increase. Moreover, due to evaporation, the pheromone concentration in the longer path reduces, decreasing the probability of selection of this path in further stages. Therefore, the whole colony gradually uses the shorter path in higher probabilities. So, path optimization is attained."
},
{
"code": null,
"e": 4489,
"s": 4291,
"text": "Stage 1: All ants are in their nest. There is no pheromone content in the environment. (For algorithmic design, residual pheromone amount can be considered without interfering with the probability)"
},
{
"code": null,
"e": 4693,
"s": 4489,
"text": "Stage 2: Ants begin their search with equal (0.5 each) probability along each path. Clearly, the curved path is the longer and hence the time taken by ants to reach food source is greater than the other."
},
{
"code": null,
"e": 4939,
"s": 4693,
"text": "Stage 3: The ants through the shorter path reaches food source earlier. Now, evidently they face with a similar selection dilemma, but this time due to pheromone trail along the shorter path already available, probability of selection is higher."
},
{
"code": null,
"e": 5325,
"s": 4939,
"text": "Stage 4: More ants return via the shorter path and subsequently the pheromone concentrations also increase. Moreover, due to evaporation, the pheromone concentration in the longer path reduces, decreasing the probability of selection of this path in further stages. Therefore, the whole colony gradually uses the shorter path in higher probabilities. So, path optimization is attained."
},
{
"code": null,
"e": 5345,
"s": 5325,
"text": "Algorithmic Design:"
},
{
"code": null,
"e": 6309,
"s": 5345,
"text": "Pertaining to the above behaviour of the ants, an algorithmic design can now be developed. For simplicity, a single food source and single ant colony have been considered with just two paths of possible traversal. The whole scenario can be realized through weighted graphs where the ant colony and the food source act as vertices (or nodes); the paths serve as the edges and the pheromone values are the weights associated with the edges.Let the graph be G = (V, E) where V, E are the edges and the vertices of the graph. The vertices according to our consideration are Vs (Source vertex – ant colony) and Vd (Destination vertex – Food source), The two edges are E1 and E2 with lengths L1 and L2 assigned to each. Now, the associated pheromone values (indicative of their strength) can be assumed to be R1 and R2 for vertices E1 and E2 respectively. Thus for each ant, the starting probability of selection of path (between E1 and E2) can be expressed as follows:"
},
{
"code": null,
"e": 6655,
"s": 6309,
"text": "Evidently, if R1>R2, the probability of choosing E1 is higher and vice-versa. Now, while returning through this shortest path say Ei, the pheromone value is updated for the corresponding path. The updation is done based on the length of the paths as well as the evaporation rate of pheromone. So, the update can be step-wise realized as follows:"
},
{
"code": null,
"e": 7021,
"s": 6655,
"text": "In accordance to path length –In the above updation, i = 1, 2 and ‘K’ serves as a parameter of the model. Moreover, the update is dependent on the length of the path. Shorter the path, higher the pheromone added.In accordance to evaporation rate of pheromone –The parameter ‘v’ belongs to interval (0, 1] that regulates the pheromone evaporation. Further, i = 1, 2."
},
{
"code": null,
"e": 7234,
"s": 7021,
"text": "In accordance to path length –In the above updation, i = 1, 2 and ‘K’ serves as a parameter of the model. Moreover, the update is dependent on the length of the path. Shorter the path, higher the pheromone added."
},
{
"code": null,
"e": 7388,
"s": 7234,
"text": "In accordance to evaporation rate of pheromone –The parameter ‘v’ belongs to interval (0, 1] that regulates the pheromone evaporation. Further, i = 1, 2."
},
{
"code": null,
"e": 7621,
"s": 7388,
"text": "At each iteration, all ants are placed at source vertex Vs (ant colony). Subsequently, ants move from Vs to Vd (food source) following step 1. Next, all ants conduct their return trip and reinforce their chosen path based on step 2."
},
{
"code": null,
"e": 7633,
"s": 7621,
"text": "Pseudocode:"
},
{
"code": null,
"e": 7961,
"s": 7633,
"text": "Procedure AntColonyOptimization:\n Initialize necessary parameters and pheromone trials;\n while not termination do:\n Generate ant population;\n Calculate fitness values associated with each ant;\n Find best solution through selection methods;\n Update pheromone trial;\n end while\nend procedure\n"
},
{
"code": null,
"e": 8298,
"s": 7961,
"text": "The pheromone update and the fitness calculations in the above pseudocode can be found through the step-wise implementations mentioned above.Thus, the introduction of the ACO optimization technique has been established. The application of the ACO can be extended to various problems such as the famous TSP (Travelling Salesman Problem)."
},
{
"code": null,
"e": 8378,
"s": 8298,
"text": "References:https://www.ics.uci.edu/~welling/teaching/271fall09/antcolonyopt.pdf"
},
{
"code": null,
"e": 8402,
"s": 8378,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 8421,
"s": 8402,
"text": "Genetic Algorithms"
},
{
"code": null,
"e": 8438,
"s": 8421,
"text": "Machine Learning"
},
{
"code": null,
"e": 8454,
"s": 8438,
"text": "Write From Home"
},
{
"code": null,
"e": 8471,
"s": 8454,
"text": "Machine Learning"
}
]
|
Python | Sort Python Dictionaries by Key or Value | 01 Jul, 2022
In this article, we will discuss how we sort a dictionary by value and keys in Python.
We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Therefore sorting is very important when we are dealing with a large amount of data. Here, we will use the following approach:
First, sort the keys alphabetically using key_value.iterkeys() function.
Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))
Here are the major tasks that are needed to be performed sort a dictionary by value and keys in Python.
Create a dictionary and display its list-keys alphabetically.Display both the keys and values sorted in alphabetical order by the key.Same as part (ii), but sorted in alphabetical order by the value.
Create a dictionary and display its list-keys alphabetically.
Display both the keys and values sorted in alphabetical order by the key.
Same as part (ii), but sorted in alphabetical order by the value.
In this example, we are trying to sort the dictionary by keys and values in Python. Here, iterkeys() returns an iterator over the dictionary’s keys.
Input:
key_value[2] = '56'
key_value[1] = '2'
key_value[4] = '12'
key_value[5] = '24'
key_value[6] = '18'
key_value[3] = '323'
Output:
1 2 3 4 5 6
Python3
# Function callingdef dictionairy(): # Declare hash function key_value = {} # Initializing value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("Task 1:-\n") print("key_value", key_value) # iterkeys() returns an iterator over the # dictionary’s keys. for i in sorted(key_value.keys()): print(i, end=" ") def main(): # function calling dictionairy() # Main function callingif __name__ == "__main__": main()
Output:
Task 1:-
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
1 2 3 4 5 6
In this example, we will sort in lexicographical order Taking the key’s type as a string.
Input:
key_value['ravi'] = '10'
key_value['rajnish'] = '9'
key_value['sanjeev'] = '15'
key_value['yash'] = '2'
key_value'suraj'] = '32'
Output:
[('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')]
Python3
# Creates a sorted dictionary (sorted by key)from collections import OrderedDict dict = {'ravi': '10', 'rajnish': '9', 'sanjeev': '15', 'yash': '2', 'suraj': '32'}dict1 = OrderedDict(sorted(dict.items()))print(dict1)
Output:
OrderedDict([('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')])
In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using an iterator over the Dictionary’s value to sort the keys.
Input:
key_value[2] = '56'
key_value[1] = '2'
key_value[4] = '12'
key_value[5] = '24'
key_value[6] = '18'
key_value[3] = '323'
Output:
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Python3
# function callingdef dictionairy(): # Declaring the hash function key_value = {} # Initialize value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value",key_value) print("Task 2:-\nKeys and Values sorted in", "alphabetical order by the key ") # sorted(key_value) returns an iterator over the # Dictionary’s value sorted in keys. for i in sorted(key_value): print((i, key_value[i]), end=" ") def main(): # function calling dictionairy() # main function callingif __name__ == "__main__": main()
Output:
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
Task 2:-
Keys and Values sorted in alphabetical order by the key
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order.
Input:
key_value[2] = '56'
key_value[1] = '2'
key_value[4] = '12'
key_value[5] = '24'
key_value[6] = '18'
key_value[3] = '323'
Output:
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]
Python3
# Function callingdef dictionairy(): # Declaring hash function key_value = {} # Initializing the value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value",key_value) print("Task 3:-\nKeys and Values sorted", "in alphabetical order by the value") # Note that it will sort in lexicographical order # For mathematical way, change it to float print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))) def main(): # function calling dictionairy() # main function callingif __name__ == "__main__": main()
Output:
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
Task 3:-
Keys and Values sorted in alphabetical order by the value
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]
In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values.
Input:
key_value['ravi'] = 10
key_value['rajnish'] = 9
key_value['sanjeev'] = 15
key_value['yash'] = 2
key_value'suraj'] = 32
Output:
{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}
Python3
# Creates a sorted dictionary (sorted by key)from collections import OrderedDict dict = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}print(dict) sorted_value_index = np.argsort(dict.values())dictionary_keys = list(dict.keys())sorted_dict = {dictionary_keys[i]: sorted( dict.values())[i] for i in range(len(dictionary_keys))} print(sorted_dict)
Output:
{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}
ravikishor
rajeev0719singh
surajkumarguptaintern
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 141,
"s": 54,
"text": "In this article, we will discuss how we sort a dictionary by value and keys in Python."
},
{
"code": null,
"e": 373,
"s": 141,
"text": "We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Therefore sorting is very important when we are dealing with a large amount of data. Here, we will use the following approach:"
},
{
"code": null,
"e": 446,
"s": 373,
"text": "First, sort the keys alphabetically using key_value.iterkeys() function."
},
{
"code": null,
"e": 560,
"s": 446,
"text": "Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it."
},
{
"code": null,
"e": 657,
"s": 560,
"text": "Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))"
},
{
"code": null,
"e": 761,
"s": 657,
"text": "Here are the major tasks that are needed to be performed sort a dictionary by value and keys in Python."
},
{
"code": null,
"e": 961,
"s": 761,
"text": "Create a dictionary and display its list-keys alphabetically.Display both the keys and values sorted in alphabetical order by the key.Same as part (ii), but sorted in alphabetical order by the value."
},
{
"code": null,
"e": 1023,
"s": 961,
"text": "Create a dictionary and display its list-keys alphabetically."
},
{
"code": null,
"e": 1097,
"s": 1023,
"text": "Display both the keys and values sorted in alphabetical order by the key."
},
{
"code": null,
"e": 1163,
"s": 1097,
"text": "Same as part (ii), but sorted in alphabetical order by the value."
},
{
"code": null,
"e": 1312,
"s": 1163,
"text": "In this example, we are trying to sort the dictionary by keys and values in Python. Here, iterkeys() returns an iterator over the dictionary’s keys."
},
{
"code": null,
"e": 1468,
"s": 1312,
"text": "Input:\nkey_value[2] = '56' \nkey_value[1] = '2'\nkey_value[4] = '12'\nkey_value[5] = '24'\nkey_value[6] = '18'\nkey_value[3] = '323'\n\nOutput:\n1 2 3 4 5 6 "
},
{
"code": null,
"e": 1476,
"s": 1468,
"text": "Python3"
},
{
"code": "# Function callingdef dictionairy(): # Declare hash function key_value = {} # Initializing value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print(\"Task 1:-\\n\") print(\"key_value\", key_value) # iterkeys() returns an iterator over the # dictionary’s keys. for i in sorted(key_value.keys()): print(i, end=\" \") def main(): # function calling dictionairy() # Main function callingif __name__ == \"__main__\": main()",
"e": 2009,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2017,
"s": 2009,
"text": "Output:"
},
{
"code": null,
"e": 2094,
"s": 2017,
"text": "Task 1:-\n\nkey_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}\n\n1 2 3 4 5 6 "
},
{
"code": null,
"e": 2184,
"s": 2094,
"text": "In this example, we will sort in lexicographical order Taking the key’s type as a string."
},
{
"code": null,
"e": 2422,
"s": 2184,
"text": "Input:\nkey_value['ravi'] = '10' \nkey_value['rajnish'] = '9'\nkey_value['sanjeev'] = '15'\nkey_value['yash'] = '2'\nkey_value'suraj'] = '32'\n\nOutput:\n[('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')]"
},
{
"code": null,
"e": 2430,
"s": 2422,
"text": "Python3"
},
{
"code": "# Creates a sorted dictionary (sorted by key)from collections import OrderedDict dict = {'ravi': '10', 'rajnish': '9', 'sanjeev': '15', 'yash': '2', 'suraj': '32'}dict1 = OrderedDict(sorted(dict.items()))print(dict1)",
"e": 2654,
"s": 2430,
"text": null
},
{
"code": null,
"e": 2662,
"s": 2654,
"text": "Output:"
},
{
"code": null,
"e": 2761,
"s": 2662,
"text": "OrderedDict([('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')])"
},
{
"code": null,
"e": 2921,
"s": 2761,
"text": "In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using an iterator over the Dictionary’s value to sort the keys."
},
{
"code": null,
"e": 3113,
"s": 2921,
"text": "Input:\nkey_value[2] = '56' \nkey_value[1] = '2'\nkey_value[4] = '12'\nkey_value[5] = '24'\nkey_value[6] = '18'\nkey_value[3] = '323'\n\nOutput:\n(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) "
},
{
"code": null,
"e": 3121,
"s": 3113,
"text": "Python3"
},
{
"code": "# function callingdef dictionairy(): # Declaring the hash function key_value = {} # Initialize value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print(\"key_value\",key_value) print(\"Task 2:-\\nKeys and Values sorted in\", \"alphabetical order by the key \") # sorted(key_value) returns an iterator over the # Dictionary’s value sorted in keys. for i in sorted(key_value): print((i, key_value[i]), end=\" \") def main(): # function calling dictionairy() # main function callingif __name__ == \"__main__\": main()",
"e": 3772,
"s": 3121,
"text": null
},
{
"code": null,
"e": 3780,
"s": 3772,
"text": "Output:"
},
{
"code": null,
"e": 3949,
"s": 3780,
"text": "key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}\nTask 2:-\nKeys and Values sorted in alphabetical order by the key \n(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) "
},
{
"code": null,
"e": 4085,
"s": 3949,
"text": "In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order."
},
{
"code": null,
"e": 4283,
"s": 4085,
"text": "Input:\nkey_value[2] = '56' \nkey_value[1] = '2'\nkey_value[4] = '12'\nkey_value[5] = '24'\nkey_value[6] = '18'\nkey_value[3] = '323'\n\nOutput:\n[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]"
},
{
"code": null,
"e": 4291,
"s": 4283,
"text": "Python3"
},
{
"code": "# Function callingdef dictionairy(): # Declaring hash function key_value = {} # Initializing the value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print(\"key_value\",key_value) print(\"Task 3:-\\nKeys and Values sorted\", \"in alphabetical order by the value\") # Note that it will sort in lexicographical order # For mathematical way, change it to float print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))) def main(): # function calling dictionairy() # main function callingif __name__ == \"__main__\": main()",
"e": 4953,
"s": 4291,
"text": null
},
{
"code": null,
"e": 4961,
"s": 4953,
"text": "Output:"
},
{
"code": null,
"e": 5136,
"s": 4961,
"text": "key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}\nTask 3:-\nKeys and Values sorted in alphabetical order by the value\n[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]"
},
{
"code": null,
"e": 5274,
"s": 5136,
"text": "In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values."
},
{
"code": null,
"e": 5482,
"s": 5274,
"text": "Input:\nkey_value['ravi'] = 10 \nkey_value['rajnish'] = 9\nkey_value['sanjeev'] = 15\nkey_value['yash'] = 2\nkey_value'suraj'] = 32\n\nOutput:\n{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}"
},
{
"code": null,
"e": 5490,
"s": 5482,
"text": "Python3"
},
{
"code": "# Creates a sorted dictionary (sorted by key)from collections import OrderedDict dict = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}print(dict) sorted_value_index = np.argsort(dict.values())dictionary_keys = list(dict.keys())sorted_dict = {dictionary_keys[i]: sorted( dict.values())[i] for i in range(len(dictionary_keys))} print(sorted_dict)",
"e": 5864,
"s": 5490,
"text": null
},
{
"code": null,
"e": 5872,
"s": 5864,
"text": "Output:"
},
{
"code": null,
"e": 6004,
"s": 5872,
"text": "{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}\n{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}"
},
{
"code": null,
"e": 6015,
"s": 6004,
"text": "ravikishor"
},
{
"code": null,
"e": 6031,
"s": 6015,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 6053,
"s": 6031,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 6080,
"s": 6053,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 6092,
"s": 6080,
"text": "python-dict"
},
{
"code": null,
"e": 6099,
"s": 6092,
"text": "Python"
},
{
"code": null,
"e": 6111,
"s": 6099,
"text": "python-dict"
}
]
|
Python program to sort a list of tuples by second Item | 19 May, 2022
Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple. Examples:
Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)]
Output : [('Geeks', 8), ('for', 24), ('Geeks', 30)]
Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)]
Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]
Method #1: Using the Bubble Sort Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the second element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
Python3
# Python program to sort a list of tuples by the second Item # Function to sort the list of tuples by its second itemdef Sort_Tuple(tup): # getting length of list of tuples lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Driver Codetup =[('for', 24), ('is', 10), ('Geeks', 28), ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)] print(Sort_Tuple(tup))
Output:
[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]
Method #2: Using sort() method While sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed.
Python3
# Python program to sort a list of# tuples by the second Item using sort() # Function to sort the list by second item of tupledef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used tup.sort(key = lambda x: x[1]) return tup # Driver Codetup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] # printing the sorted list of tuplesprint(Sort_Tuple(tup))
Output:
[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]
Method #3: Using sorted() method Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three: Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. Key(optional) : A function that would serve as a key or a basis of sort comparison. Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
Python3
# Python program to sort a list of# tuples by the second Item using sorted() # Function to sort the list by second item of tupledef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used return(sorted(tup, key = lambda x: x[1])) # Driver Codetup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] # printing the sorted list of tuplesprint(Sort_Tuple(tup))
Output:
[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]
rohitlal125555
sumitgumber28
Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 162,
"s": 52,
"text": "Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple. Examples:"
},
{
"code": null,
"e": 388,
"s": 162,
"text": "Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)] \nOutput : [('Geeks', 8), ('for', 24), ('Geeks', 30)]\n\nInput : [('452', 10), ('256', 5), ('100', 20), ('135', 15)]\nOutput : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]"
},
{
"code": null,
"e": 717,
"s": 388,
"text": " Method #1: Using the Bubble Sort Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the second element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2). "
},
{
"code": null,
"e": 725,
"s": 717,
"text": "Python3"
},
{
"code": "# Python program to sort a list of tuples by the second Item # Function to sort the list of tuples by its second itemdef Sort_Tuple(tup): # getting length of list of tuples lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][1] > tup[j + 1][1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup # Driver Codetup =[('for', 24), ('is', 10), ('Geeks', 28), ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)] print(Sort_Tuple(tup))",
"e": 1289,
"s": 725,
"text": null
},
{
"code": null,
"e": 1297,
"s": 1289,
"text": "Output:"
},
{
"code": null,
"e": 1387,
"s": 1297,
"text": "[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]"
},
{
"code": null,
"e": 1576,
"s": 1387,
"text": " Method #2: Using sort() method While sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed. "
},
{
"code": null,
"e": 1584,
"s": 1576,
"text": "Python3"
},
{
"code": "# Python program to sort a list of# tuples by the second Item using sort() # Function to sort the list by second item of tupledef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used tup.sort(key = lambda x: x[1]) return tup # Driver Codetup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] # printing the sorted list of tuplesprint(Sort_Tuple(tup))",
"e": 2047,
"s": 1584,
"text": null
},
{
"code": null,
"e": 2055,
"s": 2047,
"text": "Output:"
},
{
"code": null,
"e": 2115,
"s": 2055,
"text": "[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]"
},
{
"code": null,
"e": 2834,
"s": 2115,
"text": " Method #3: Using sorted() method Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three: Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. Key(optional) : A function that would serve as a key or a basis of sort comparison. Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false. "
},
{
"code": null,
"e": 2842,
"s": 2834,
"text": "Python3"
},
{
"code": "# Python program to sort a list of# tuples by the second Item using sorted() # Function to sort the list by second item of tupledef Sort_Tuple(tup): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used return(sorted(tup, key = lambda x: x[1])) # Driver Codetup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)] # printing the sorted list of tuplesprint(Sort_Tuple(tup))",
"e": 3305,
"s": 2842,
"text": null
},
{
"code": null,
"e": 3313,
"s": 3305,
"text": "Output:"
},
{
"code": null,
"e": 3373,
"s": 3313,
"text": "[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]"
},
{
"code": null,
"e": 3388,
"s": 3373,
"text": "rohitlal125555"
},
{
"code": null,
"e": 3402,
"s": 3388,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3423,
"s": 3402,
"text": "Python list-programs"
},
{
"code": null,
"e": 3445,
"s": 3423,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 3457,
"s": 3445,
"text": "python-list"
},
{
"code": null,
"e": 3470,
"s": 3457,
"text": "python-tuple"
},
{
"code": null,
"e": 3477,
"s": 3470,
"text": "Python"
},
{
"code": null,
"e": 3493,
"s": 3477,
"text": "Python Programs"
},
{
"code": null,
"e": 3512,
"s": 3493,
"text": "School Programming"
},
{
"code": null,
"e": 3524,
"s": 3512,
"text": "python-list"
}
]
|
Building a Chat Bot With Object Detection and OCR | by Mitchell A. Carroll | Towards Data Science | In part 1 of this series, we gave our bot the ability to detect sentiment from text and respond accordingly. But that’s about all it can do, and admittedly quite boring.
Of course, in a real chat, we often send a multitude of media: from text, images, videos, gifs, to anything else. So in this, our next step in our journey, let’s give our bot vision. The goal of this tutorial is to allow our bot to receive images, reply to them, and eventually give us a crude description of the main object in said image.
Let’s get started!
If you haven’t followed along, you can find the latest code here:
So the code we want to modify is in our event response cycle method, here:
Our bot already responds to images, but it has no idea what they are and responds in a rather bland way.
We can try it out, and see for ourselves. Let’s fire up our server (and ngrok), and send our bot an image.
So far so good. Our bot at least knows when it receives an image.
In this series, we have been using google cloud APIs, so for our image detection, we’ll be using Google Cloud Vision. Follow the quick-start here to get your project all set up: https://cloud.google.com/vision/docs/quickstart-client-libraries. Remember to use the same project that we set up in part 1.
Once you have completed that, now it’s time to get back to coding. Let’s add the following to our Gemfile and run bundle install:
gem 'google-cloud-vision'
Let’s require it in main.rb by adding the following:
require ‘google/cloud/vision’
Next, we want to create an instance of the cloud language API:
The vision API feature that we want to use is called annotation. Given a file path to an image on your local machine, it will attempt to identify the image based on values we pass to the method call.
In the following example (from Google’s documentation):
vision = Google::Cloud::Vision.newimage = vision.image "path/to/face.jpg"annotation = vision.annotate image, faces: true, labels: trueannotation.faces.count #=> 1annotation.labels.count #=> 4annotation.text #=> nil
We are telling the vision API attempt to recognize faces and labels. “Labels” are essentially objects that the API determines it has identified. Provided a picture of a dog, we would potentially be given the following labels:
{ "responses": [ { "labelAnnotations": [ { "mid": "/m/0bt9lr", "description": "dog", "score": 0.97346616 }, { "mid": "/m/09686", "description": "vertebrate", "score": 0.85700572 }, { "mid": "/m/01pm38", "description": "clumber spaniel", "score": 0.84881884 }, { "mid": "/m/04rky", "description": "mammal", "score": 0.847575 }, { "mid": "/m/02wbgd", "description": "english cocker spaniel", "score": 0.75829375 } ] } ]}
Let’s create the following method to utilize this functionality:
The above (admittedly naive) method takes a file path and returns a string, based on the results of the Google cloud vision’s API. In the annotate method, we are passing a few parameters, which tells the API what we want to try to detect.
The return (response) for this method is a cascading short-circuit flow, first checking for famous landmarks, any text, and finally any objects (labels) it has detected. This flow is purely arbitrary and simplified for purposes of this tutorial (i.e. don’t email me about how it can be improved).
Let’s try it on the following picture:
And the results (truncated):
description: "cuisine", score: 0.9247923493385315, confidence: 0.0, topicality: 0.9247923493385315, bounds: 0, locations: 0, properties: {}description: "sushi", score: 0.9149415493011475, confidence: 0.0, topicality: 0.9149415493011475, bounds: 0, locations: 0, properties: {}description: "food", score: 0.899940550327301, confidence: 0.0, topicality: 0.899940550327301, bounds: 0, locations: 0, properties: {}description: "japanese cuisine", score: 0.8769422769546509, confidence: 0.0, topicality: 0.8769422769546509, bounds: 0, locations: 0, properties: {}
Since there were no landmarks or text, we have received the labels the API was able to detect. In this case, we see that it has been identified as “sushi.” In my experience with the label detection results, the second label (having the second highest topicality) tends to be how an average person would identify the picture.
Let’s give it another go on the following:
The output (again truncated):
description: "wildlife", score: 0.9749518036842346, confidence: 0.0, topicality: 0.9749518036842346, bounds: 0, locations: 0, properties: {}description: "lion", score: 0.9627781510353088, confidence: 0.0, topicality: 0.9627781510353088, bounds: 0, locations: 0, properties: {}description: "terrestrial animal", score: 0.9247941970825195, confidence: 0.0, topicality: 0.9247941970825195, bounds: 0, locations: 0, properties: {}
And there we see it, with “lion” being the second hit.
Ok, another for good measure, let’s try some text extraction:
And let's see what we get:
2.4.2 :022 > puts analyze_image("major_general.png")I am the very model of a modern Major-General,I've information vegetable, animal, and mineral,I know the kings of England, and I quote the fights historicalFrom Marathon to Waterloo, in order categorical;I'm very well acquainted, too, with matters mathematical,I understand equations, both the simple and quadratical,About binomial theorem I'm teeming with a lot o' news, (bothered for a rhyme)With many cheerful facts about the square of the hypotenuse. => nil2.4.2 :023 >
Not bad.
Ok, last one for completeness’ sake. Let’s try a landmark:
And our method gives us:
2.4.2 :030 > puts analyze_image(“statue_of_liberty.jpg”)Statue of Liberty
Ok, so our method is working as intended, now let’s actually use it with our chatbot.
When we send an image to our chatbot through our client (Line), the client returns the image data in the response body (along with other relevant information) to our callback. Because our image recognition method needs a file path, we will have to save the aforementioned image data to our local machine.
Let’s modify our method to do that. Change the relevant parts of your callback method to the following:
There is a bit going on here. First, we are creating a new Tempfile, and using the response body (image data) as its content. We’re then passing the tempfile’s path to the analye_image method we just tested in the console. Let’s try it with our bot, just as a sanity check.
And it was able to successfully identify a landmark for us.
Our bot is now just working as a glorified console print line, and that’s not very chatty at all. We want this thing to sound more natural, let’s clean up our method a bit to make it sound more “human”.
Let’s make the necessary changes to our code. We’ll be modifying an existing method analyze_image and creating a new method get_analyze_image_response. Here it is below:
Again, this is not a tutorial about Ruby, but rather concepts; however, let’s go over what we’ve just done. In analyze_image we simply removed the string reply and replaced it with our new method get_analyze_image_response. This method takes an annotation object, and based on the type of object identified in the image, builds a sentence (string) using the annotation object’s description values.
Let’s try it out!
A classic:
And now a landmark:
And that’s it! Our bot now extracts text from images using optical character recognition, and also give us a basic description of objects it finds in any image we send it.
Currently, our bot can only reply to one-off messages. But what if it had a “memory”, and was able to actually able to have a real conversation? We will cover multi-step communication in Part 3.
Below is all of our code up to this point: | [
{
"code": null,
"e": 342,
"s": 172,
"text": "In part 1 of this series, we gave our bot the ability to detect sentiment from text and respond accordingly. But that’s about all it can do, and admittedly quite boring."
},
{
"code": null,
"e": 682,
"s": 342,
"text": "Of course, in a real chat, we often send a multitude of media: from text, images, videos, gifs, to anything else. So in this, our next step in our journey, let’s give our bot vision. The goal of this tutorial is to allow our bot to receive images, reply to them, and eventually give us a crude description of the main object in said image."
},
{
"code": null,
"e": 701,
"s": 682,
"text": "Let’s get started!"
},
{
"code": null,
"e": 767,
"s": 701,
"text": "If you haven’t followed along, you can find the latest code here:"
},
{
"code": null,
"e": 842,
"s": 767,
"text": "So the code we want to modify is in our event response cycle method, here:"
},
{
"code": null,
"e": 947,
"s": 842,
"text": "Our bot already responds to images, but it has no idea what they are and responds in a rather bland way."
},
{
"code": null,
"e": 1054,
"s": 947,
"text": "We can try it out, and see for ourselves. Let’s fire up our server (and ngrok), and send our bot an image."
},
{
"code": null,
"e": 1120,
"s": 1054,
"text": "So far so good. Our bot at least knows when it receives an image."
},
{
"code": null,
"e": 1423,
"s": 1120,
"text": "In this series, we have been using google cloud APIs, so for our image detection, we’ll be using Google Cloud Vision. Follow the quick-start here to get your project all set up: https://cloud.google.com/vision/docs/quickstart-client-libraries. Remember to use the same project that we set up in part 1."
},
{
"code": null,
"e": 1553,
"s": 1423,
"text": "Once you have completed that, now it’s time to get back to coding. Let’s add the following to our Gemfile and run bundle install:"
},
{
"code": null,
"e": 1579,
"s": 1553,
"text": "gem 'google-cloud-vision'"
},
{
"code": null,
"e": 1632,
"s": 1579,
"text": "Let’s require it in main.rb by adding the following:"
},
{
"code": null,
"e": 1662,
"s": 1632,
"text": "require ‘google/cloud/vision’"
},
{
"code": null,
"e": 1725,
"s": 1662,
"text": "Next, we want to create an instance of the cloud language API:"
},
{
"code": null,
"e": 1925,
"s": 1725,
"text": "The vision API feature that we want to use is called annotation. Given a file path to an image on your local machine, it will attempt to identify the image based on values we pass to the method call."
},
{
"code": null,
"e": 1981,
"s": 1925,
"text": "In the following example (from Google’s documentation):"
},
{
"code": null,
"e": 2196,
"s": 1981,
"text": "vision = Google::Cloud::Vision.newimage = vision.image \"path/to/face.jpg\"annotation = vision.annotate image, faces: true, labels: trueannotation.faces.count #=> 1annotation.labels.count #=> 4annotation.text #=> nil"
},
{
"code": null,
"e": 2422,
"s": 2196,
"text": "We are telling the vision API attempt to recognize faces and labels. “Labels” are essentially objects that the API determines it has identified. Provided a picture of a dog, we would potentially be given the following labels:"
},
{
"code": null,
"e": 3064,
"s": 2422,
"text": "{ \"responses\": [ { \"labelAnnotations\": [ { \"mid\": \"/m/0bt9lr\", \"description\": \"dog\", \"score\": 0.97346616 }, { \"mid\": \"/m/09686\", \"description\": \"vertebrate\", \"score\": 0.85700572 }, { \"mid\": \"/m/01pm38\", \"description\": \"clumber spaniel\", \"score\": 0.84881884 }, { \"mid\": \"/m/04rky\", \"description\": \"mammal\", \"score\": 0.847575 }, { \"mid\": \"/m/02wbgd\", \"description\": \"english cocker spaniel\", \"score\": 0.75829375 } ] } ]}"
},
{
"code": null,
"e": 3129,
"s": 3064,
"text": "Let’s create the following method to utilize this functionality:"
},
{
"code": null,
"e": 3368,
"s": 3129,
"text": "The above (admittedly naive) method takes a file path and returns a string, based on the results of the Google cloud vision’s API. In the annotate method, we are passing a few parameters, which tells the API what we want to try to detect."
},
{
"code": null,
"e": 3665,
"s": 3368,
"text": "The return (response) for this method is a cascading short-circuit flow, first checking for famous landmarks, any text, and finally any objects (labels) it has detected. This flow is purely arbitrary and simplified for purposes of this tutorial (i.e. don’t email me about how it can be improved)."
},
{
"code": null,
"e": 3704,
"s": 3665,
"text": "Let’s try it on the following picture:"
},
{
"code": null,
"e": 3733,
"s": 3704,
"text": "And the results (truncated):"
},
{
"code": null,
"e": 4292,
"s": 3733,
"text": "description: \"cuisine\", score: 0.9247923493385315, confidence: 0.0, topicality: 0.9247923493385315, bounds: 0, locations: 0, properties: {}description: \"sushi\", score: 0.9149415493011475, confidence: 0.0, topicality: 0.9149415493011475, bounds: 0, locations: 0, properties: {}description: \"food\", score: 0.899940550327301, confidence: 0.0, topicality: 0.899940550327301, bounds: 0, locations: 0, properties: {}description: \"japanese cuisine\", score: 0.8769422769546509, confidence: 0.0, topicality: 0.8769422769546509, bounds: 0, locations: 0, properties: {}"
},
{
"code": null,
"e": 4617,
"s": 4292,
"text": "Since there were no landmarks or text, we have received the labels the API was able to detect. In this case, we see that it has been identified as “sushi.” In my experience with the label detection results, the second label (having the second highest topicality) tends to be how an average person would identify the picture."
},
{
"code": null,
"e": 4660,
"s": 4617,
"text": "Let’s give it another go on the following:"
},
{
"code": null,
"e": 4690,
"s": 4660,
"text": "The output (again truncated):"
},
{
"code": null,
"e": 5117,
"s": 4690,
"text": "description: \"wildlife\", score: 0.9749518036842346, confidence: 0.0, topicality: 0.9749518036842346, bounds: 0, locations: 0, properties: {}description: \"lion\", score: 0.9627781510353088, confidence: 0.0, topicality: 0.9627781510353088, bounds: 0, locations: 0, properties: {}description: \"terrestrial animal\", score: 0.9247941970825195, confidence: 0.0, topicality: 0.9247941970825195, bounds: 0, locations: 0, properties: {}"
},
{
"code": null,
"e": 5172,
"s": 5117,
"text": "And there we see it, with “lion” being the second hit."
},
{
"code": null,
"e": 5234,
"s": 5172,
"text": "Ok, another for good measure, let’s try some text extraction:"
},
{
"code": null,
"e": 5261,
"s": 5234,
"text": "And let's see what we get:"
},
{
"code": null,
"e": 5787,
"s": 5261,
"text": "2.4.2 :022 > puts analyze_image(\"major_general.png\")I am the very model of a modern Major-General,I've information vegetable, animal, and mineral,I know the kings of England, and I quote the fights historicalFrom Marathon to Waterloo, in order categorical;I'm very well acquainted, too, with matters mathematical,I understand equations, both the simple and quadratical,About binomial theorem I'm teeming with a lot o' news, (bothered for a rhyme)With many cheerful facts about the square of the hypotenuse. => nil2.4.2 :023 >"
},
{
"code": null,
"e": 5796,
"s": 5787,
"text": "Not bad."
},
{
"code": null,
"e": 5855,
"s": 5796,
"text": "Ok, last one for completeness’ sake. Let’s try a landmark:"
},
{
"code": null,
"e": 5880,
"s": 5855,
"text": "And our method gives us:"
},
{
"code": null,
"e": 5954,
"s": 5880,
"text": "2.4.2 :030 > puts analyze_image(“statue_of_liberty.jpg”)Statue of Liberty"
},
{
"code": null,
"e": 6040,
"s": 5954,
"text": "Ok, so our method is working as intended, now let’s actually use it with our chatbot."
},
{
"code": null,
"e": 6345,
"s": 6040,
"text": "When we send an image to our chatbot through our client (Line), the client returns the image data in the response body (along with other relevant information) to our callback. Because our image recognition method needs a file path, we will have to save the aforementioned image data to our local machine."
},
{
"code": null,
"e": 6449,
"s": 6345,
"text": "Let’s modify our method to do that. Change the relevant parts of your callback method to the following:"
},
{
"code": null,
"e": 6723,
"s": 6449,
"text": "There is a bit going on here. First, we are creating a new Tempfile, and using the response body (image data) as its content. We’re then passing the tempfile’s path to the analye_image method we just tested in the console. Let’s try it with our bot, just as a sanity check."
},
{
"code": null,
"e": 6783,
"s": 6723,
"text": "And it was able to successfully identify a landmark for us."
},
{
"code": null,
"e": 6986,
"s": 6783,
"text": "Our bot is now just working as a glorified console print line, and that’s not very chatty at all. We want this thing to sound more natural, let’s clean up our method a bit to make it sound more “human”."
},
{
"code": null,
"e": 7156,
"s": 6986,
"text": "Let’s make the necessary changes to our code. We’ll be modifying an existing method analyze_image and creating a new method get_analyze_image_response. Here it is below:"
},
{
"code": null,
"e": 7554,
"s": 7156,
"text": "Again, this is not a tutorial about Ruby, but rather concepts; however, let’s go over what we’ve just done. In analyze_image we simply removed the string reply and replaced it with our new method get_analyze_image_response. This method takes an annotation object, and based on the type of object identified in the image, builds a sentence (string) using the annotation object’s description values."
},
{
"code": null,
"e": 7572,
"s": 7554,
"text": "Let’s try it out!"
},
{
"code": null,
"e": 7583,
"s": 7572,
"text": "A classic:"
},
{
"code": null,
"e": 7603,
"s": 7583,
"text": "And now a landmark:"
},
{
"code": null,
"e": 7775,
"s": 7603,
"text": "And that’s it! Our bot now extracts text from images using optical character recognition, and also give us a basic description of objects it finds in any image we send it."
},
{
"code": null,
"e": 7970,
"s": 7775,
"text": "Currently, our bot can only reply to one-off messages. But what if it had a “memory”, and was able to actually able to have a real conversation? We will cover multi-step communication in Part 3."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.